C #. Net multi-process synchronous communication Shared Memory ing file Memory Mapped

Source: Internet
Author: User

There are two models for node communication: Shared memory and Messages passing ).

Memory ing files seem unfamiliar to developers hosting the world, but they are indeed Ancient technology and have a considerable position in the operating system. In fact, any communication model that wants to share data will use it behind the scenes.

What is the memory ing file?? The memory ing file allows you to retain an address space and then map the physical storage to this memory space for operations. Physical storage is file management, while memory ing files areOperating System-level memory management.

Advantages:
1. I/O and cache operations are not required to access data on disk files (especially when accessing File data );
2. Allow multiple processes running on the same machine to share data (single-host multi-process data communication is the most efficient );

By using the ing between files and memory space, applications (including multiple processes) can modify files by Directly Reading and Writing in the memory .. NET Framework 4 uses managed code to access the memory ing file by accessing the memory ing file by using the local Windows function, and manages the memory ing files in Win32.

There are two types of memory ing files:

  • Persistent memory ing File

    Persistent files are memory ing files associated with source files on disks. After the last process uses this file, the data is saved to the source file on the disk. These memory ing files are suitable for processing very large source files.

  • Non-persistent memory ing File

    A non-persistent file is a memory ing file that is not associated with the source file on the disk. When the last process uses this file, data is lost and the garbage collection function recycles the file. These files applyInter-process communication(IPC) to create shared memory.

1) share among multiple processes (a process can be assigned by a process that creates the same memory ing FilePublic name).

2) to use a memory ing file, you mustCreate a full or partial view of the memory ing File. You can also create multiple views in the same part of the memory ing file.Concurrent memory.To make the two views concurrent, the two views must be created based on the same memory ing file..

3) IfThe file is larger than the logical memory space used by the application for memory ing.(On A 32-bit computer2 GB), You also need to use multiple views.

There are two types of views: stream access view and random access view. You can use stream access view to access objects sequentially. When using persistent files, random access to the view is the preferred method.

. Net Shared Memory ing file Principle: PassMemory Manager of the Operating SystemTherefore, the file is automatically separated into multiple pages and accessed as needed. You do not need to handle memory management on your own. For example:

 

C #. Net shared memory DEMO codeAs follows:

// Persistent memory ing file: Creates a memory ing file with the specified public name based on the existing file

Using (var mmf = MemoryMappedFile. CreateFromFile (@ "c: \ Memory ing file. data", FileMode. Open, "public name "))
{
// Create with the specified offset and sizeMemory ing File View Server
Using (var accessor = mmf. CreateViewAccessor (offset, length) // offset, which can be used to control the memory location of the data storage. The size is used to control the space occupied by the storage.
{
// Marshal provides a method set for allocating unmanaged memory, copying unmanaged memory blocks, and converting hosted types into unmanaged types, other miscellaneous methods are also provided for interacting with non-hosted code.

Int size = Marshal. SizeOf (typeof (char ));

// Modify the memory ing File View
For (long I = 0; I <length; I + = size)
{
Char c = accessor. ReadChar (I );
Accessor. Write (I, ref c );
}
}
}

// Another process or thread can open an existing memory ing file with the specified name in the system memory.

Using (var mmf = MemoryMappedFile. OpenExisting ("public name "))
{
Using (var accessor = mmf. CreateViewAccessor (4000000,200 0000 ))
{
Int size = Marshal. SizeOf (typeof (char ));
For (long I = 0; I <length; I + = size)
{
Char c = accessor. ReadChar (I );
Accessor. Write (I, ref c );
}
}
}

 

// Non-persistent memory ing file: the memory ing file of the existing file not mapped to the disk

Using (MemoryMappedFile mmf = MemoryMappedFile. CreateNew ("testmap", 10000 ))
{
Bool mutexCreated;
// Process Synchronization
Mutex mutex = newMutex (true, "testmapmutex", out mutexCreated );
Using (var stream = mmf. CreateViewStream () // create a file memory view stream based on stream operations
{
Var writer = newBinaryWriter (stream );
Writer. Write (1 );
}
Mutex. ReleaseMutex ();

Console. WriteLine ("Start Process B and press ENTER to continue .");
Console. ReadLine ();

 

Mutex. WaitOne ();
Using (MemoryMappedViewStream stream = mmf. CreateViewStream ())
{
Var reader = newBinaryReader (stream );
Console. WriteLine ("Process A says: {0}", reader. ReadBoolean ());
Console. WriteLine ("Process B says: {0}", reader. ReadBoolean ());
}
Mutex. ReleaseMutex ();
}

Using (MemoryMappedFile mmf = MemoryMappedFile. OpenExisting ("testmap "))
{
Mutex mutex = Mutex. OpenExisting ("testmapmutex ");
Mutex. WaitOne ();
Using (var stream = mmf. CreateViewStream (1, 0) // pay attention to the offset here
{
Var writer = newBinaryWriter (stream );
Writer. Write (0 );
}
Mutex. ReleaseMutex ();

}

 

C #. Net shared memory for inter-process communicationComplete example: the example of non-persistent communication in C # shared memory does not affect the thread and process control during communication. The following is the implementation code.

Start the Message Service IMServer_Message first,

Restart the Status Service IMServer_State,

IMServer_Message: Press enter once (create a shared memory public name and a public thread lock, and write shared memory in view stream mode ),

IMServer_State press enter once (get shared memory and view stream mode write, view accessors write struct type)

And immediately press the IMServer_Message key again (read the information just written ),

Observe the significant changes in the IMServer_State screen and wait for about 5 s (the thread lock is released ).

Observe the screen display on IMServer_Message (display the information that has just been written to the shared memory)

IMServer_Message.exe code

Using System;
Using System. IO;
Using System. IO. MemoryMappedFiles;
Using System. Runtime. InteropServices;
Using System. Threading;

Namespace IMServer_Message
{
/// <Summary>
/// Value Type struct used for shared memory communication
/// </Summary>
Public struct ServiceMsg
{
Public int Id;
Public long NowTime;
}

Internal class Program
{
Private static void Main (string [] args)
{
Console. Write ("Enter the shared memory public name (default: testmap ):");
String shareName = Console. ReadLine ();
If (string. IsNullOrEmpty (shareName ))
ShareName = "testmap ";
Using (MemoryMappedFile mmf = MemoryMappedFile. CreateOrOpen (shareName, 1024000, MemoryMappedFileAccess. ReadWrite ))
{
Bool mutexCreated;
// Process Synchronization
Var mutex = new Mutex (true, "testmapmutex", out mutexCreated );
Using (MemoryMappedViewStream stream = mmf. CreateViewStream () // create a file memory view stream
{
Var writer = new BinaryWriter (stream );
For (int I = 0; I <5; I ++)
{
Writer. Write (I );
Console. WriteLine ("{0} position write stream: {0}", I );
}
}

Mutex. ReleaseMutex ();

Console. WriteLine ("enable Status Service, press enter to read shared memory data ");
Console. ReadLine ();

Mutex. WaitOne ();
Using (MemoryMappedViewStream stream = mmf. CreateViewStream ())
{
Var reader = new BinaryReader (stream );
For (int I = 0; I <10; I ++)
{
Console. WriteLine ("{1} location: {0}", reader. ReadInt32 (), I );
}
}

Using (MemoryMappedViewAccessor accessor = mmf. CreateViewAccessor (1024,102 40 ))
{
Int colorSize = Marshal. SizeOf (typeof (ServiceMsg ));
ServiceMsg color;
For (int I = 0; I <50; I + = colorSize)
{
Accessor. Read (I, out color );
Console. WriteLine ("{1} \ tNowTime: {0}", new DateTime (color. NowTime), color. Id );
}
}
Mutex. ReleaseMutex ();
}
Console. WriteLine ("test: Im-messageservice I started !!! ");
Console. ReadKey ();
}
}
}

 

 

 

IMServer_State.exe code

Using System;
Using System. IO;
Using System. IO. MemoryMappedFiles;
Using System. Runtime. InteropServices;
Using System. Threading;

Namespace IMServer_State
{
/// <Summary>
/// Value Type struct used for shared memory communication
/// </Summary>
Public struct ServiceMsg
{
Public int Id;
Public long NowTime;
}

Internal class Program
{
Private static void Main (string [] args)
{
Console. Write ("Enter the shared memory public name (default: testmap ):");
String shareName = Console. ReadLine ();
If (string. IsNullOrEmpty (shareName ))
ShareName = "testmap ";
Using (MemoryMappedFile mmf = MemoryMappedFile. CreateOrOpen (shareName, 1024000, MemoryMappedFileAccess. ReadWrite ))
{
Mutex mutex = Mutex. OpenExisting ("testmapmutex ");
Mutex. WaitOne ();
Using (MemoryMappedViewStream stream = mmf. CreateViewStream (20, 0) // pay attention to the offset here
{
Var writer = new BinaryWriter (stream );
For (int I = 5; I <10; I ++)
{
Writer. Write (I );
Console. WriteLine ("{0} position write stream: {0}", I );
}
}
Using (MemoryMappedViewAccessor accessor = mmf. CreateViewAccessor (1024,102 40 ))
{
Int colorSize = Marshal. SizeOf (typeof (ServiceMsg ));
Var color = new ServiceMsg ();
For (int I = 0; I <colorSize * 5; I + = colorSize)
{
Color. Id = I;
Color. NowTime = DateTime. Now. Ticks;
// Accessor. Read (I, out color );
Accessor. Write (I, ref color );
Console. WriteLine ("{1} \ tNowTime: {0}", new DateTime (color. NowTime), color. Id );
Thread. Sleep (1000 );
}
}
Thread. Sleep (5000 );

Mutex. ReleaseMutex ();
}
Console. WriteLine ("test: Im-status service I started !!! ");
Console. ReadKey ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.