[r1]: / SharedMemoryWinCSharp / Program.cs  Maximize  Restore  History

Download this file

67 lines (56 with data), 2.5 kB

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using System;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Threading;

namespace SharedMemoryWin
{

    // Example structure for data exchange
    internal struct DataExchange
    {
        internal Int32 i1;
        internal Int32 i2;
    }

    class Program
    {
        static void Main(string[] args)
        {
            DataExchange dataExchangeRead, dataExchangeWrite;            
            dataExchangeWrite.i1 = 0;
            dataExchangeWrite.i2 = 0;
            
            Console.Out.WriteLine("Press 'q' to quit");

            int dataSIze = Marshal.SizeOf(typeof(DataExchange));
            
            // Open a mapped file with read access and one with write access. 
            using (var mmfRead = MemoryMappedFile.CreateOrOpen("_CODESYS_SharedMemoryTest_Write", dataSIze))
            using (var mmfWrite = MemoryMappedFile.CreateOrOpen("_CODESYS_SharedMemoryTest_Read", dataSIze))
            {
                bool quit = false;
                while (!quit)
                {
                    using (var accessorRead = mmfRead.CreateViewAccessor(0, dataSIze, MemoryMappedFileAccess.Read))
                    using (var accessorWrite = mmfWrite.CreateViewAccessor(0, dataSIze, MemoryMappedFileAccess.Write))
                    {
                        // Read the structure
                        accessorRead.Read(0, out dataExchangeRead);
                        // Write the structure
                        accessorWrite.Write(0, ref dataExchangeWrite);

                        // Display the values
                        Console.Out.Write("Read i1: {0} i2: {1}       Write i1: {2} i2: {3}\r",
                                            dataExchangeRead.i1,
                                            dataExchangeRead.i2,
                                            dataExchangeWrite.i1,
                                            dataExchangeWrite.i2);

                        // Wait a second
                        Thread.Sleep(1000);

                        // Increment sample values
                        dataExchangeWrite.i1++;
                        dataExchangeWrite.i2--;

                        // Check quit condition
                        if(Console.KeyAvailable)
                            if (Console.ReadKey().KeyChar == 'q')         
                                quit = true;
                    }
                }
            }
        }
    }
}