Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the C#.Net communication shared memory mapping file

2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the C#.Net communication shared memory mapping file". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn what the C#.Net communication shared memory mapping file is.

There are two models of node communication: shared memory (Shared memory) and message passing (Messages passing).

Memory-mapped files may seem unfamiliar to developers in the managed world, but it is indeed a very ancient technology and has a similar status in the operating system. In fact, any communication model that wants to share data will use it behind the scenes.

What on earth is a memory mapping file?

Memory mapping files allow you to reserve a piece of address space and then map the physical storage to that memory space for operation. Physical storage is file management, while memory-mapped files are operating system-level memory management.

Advantages:

1. Access to data on disk files does not require Icano and caching operations (especially when accessing file data)

two。 Let multiple processes running on the same machine share data (data communication between multiple processes on a single machine is the most efficient)

With the mapping between files and memory space, applications, including multiple processes, can modify files by reading and writing directly in memory. .net Framework 4 accesses memory-mapped files in the same way that managed code accesses memory-mapped files as native Windows functions, and manages memory-mapped files in Win32.

There are two types of memory-mapped files:

Persistent memory mapping file

A persistent file is a memory-mapped file associated with a source file on disk. After the last process finishes using this file, the data is saved to the source file on disk. These memory-mapped files are suitable for processing very large source files.

Non-persistent memory mapping file

Non-persistent files are memory-mapped files that are not associated with source files on disk. When the last process finishes using the file, the data is lost and the garbage collection feature reclaims the file. These files are used to create shared memory for interprocess communication (IPC).

1) share among multiple processes (processes can be mapped to the same memory-mapped file by using a common name assigned by the process that created the same memory-mapped file).

2) to use a memory-mapped file, you must create a full or partial view of the memory-mapped file. You can also create multiple views of the same part of a memory-mapped file, thereby creating concurrent memory. In order for two views to be concurrent, they must be created based on the same memory-mapped file.

3) if the file is larger than the logical memory space that the application uses for memory mapping (2GB on 32-bit computers), you need to use multiple views.

There are two types of views: stream access view and random access view. Use stream access views to access files sequentially; random access to views is the preferred method when using persistent files.

.net shared memory mapping file principle

Is accessed through the memory manager of the operating system, so the file is automatically separated into multiple pages and accessed as needed. You don't have to handle memory management on your own. As shown below:

C # .net shared memory demo code / / persistent memory mapping file: create a memory-mapped file using with a specified common name based on an existing file (var mmf = MemoryMappedFile.CreateFromFile (@ "c:\ memory-mapped file .data", FileMode.Open ("Common name") {/ / create a memory-mapped file view server using (var accessor = mmf.CreateViewAccessor (offset, length)) / / offset by the specified offset and size You can control the memory location of the data store Size to control the space occupied by storage {/ / Marshal provides a set of methods for allocating unmanaged memory, copying unmanaged memory blocks, converting managed types to unmanaged types, and other miscellaneous methods used when interacting with unmanaged code. Int size = Marshal.SizeOf (typeof (char)); / / modify the memory mapping 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-mapped file using (var mmf = MemoryMappedFile.OpenExisting ("common name")) {using (var accessor = mmf.CreateViewAccessor (4000000, 2000000)) {int size = Marshal.SizeOf (typeof (char)); for (long I = 0) in system memory. I < length; I + = size) {char c = accessor.ReadChar (I); accessor.Write (I, ref c);} / / non-persistent memory mapping file: memory mapping file using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew ("testmap", 10000)) that is not mapped to an existing file on disk) {bool mutexCreated / / Inter-process synchronization Mutex mutex = newMutex (true, "testmapmutex", out mutexCreated); using (var stream = mmf.CreateViewStream ()) / / create file memory view stream stream-based operation {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)) / / Note the offset here {var writer = newBinaryWriter (stream); writer.Write (0) } mutex.ReleaseMutex ();} C# .net interprocess communication shared memory

Complete example: an example of non-persistent communication in C# shared memory, and there is no problem with thread and process control when communicating.

Start the message service IMServer_Message first

Restart the status service IMServer_State

IMServer_Message enter once (create shared memory common name and common thread lock, and write shared memory in view stream)

IMServer_State enter once (get shared memory and write in view stream, view accessor writes structure type)

And immediately IMServer_Message enter again (read the information just written)

Observe the IMServer_State screen change and wait (thread lock) for about 5 seconds (thread lock is released)

Watch the screen display on the IMServer_Message (showing the information just 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 {/ value type structure for shared memory communication / public struct ServiceMsg {public int Id; public long NowTime } internal class Program {private static void Main (string [] args) {Console.Write ("Please enter the shared memory common name (default: testmap):"); string shareName = Console.ReadLine (); if (string.IsNullOrEmpty (shareName)) shareName = "testmap" Using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen (shareName, 1024000 MemoryMappedFileAccess.ReadWrite) {bool mutexCreated; / / Inter-process synchronization var mutex = new Mutex (true, "testmapmutex", out mutexCreated) Using (MemoryMappedViewStream stream = mmf.CreateViewStream ()) / / create file memory view stream {var writer = new BinaryWriter (stream); for (int I = 0; I < 5; iTunes +) {writer.Write (I) Console.WriteLine ("{0} position write stream: {0}", I);}} mutex.ReleaseMutex (); Console.WriteLine ("start status service and 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; iTunes +) {Console.WriteLine ("{1} position: {0}", reader.ReadInt32 (), I) }} using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor (1024, 10240)) {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: I am instant messaging-messaging service 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 {/ value type structure for shared memory communication / public struct ServiceMsg {public int Id; public long NowTime } internal class Program {private static void Main (string [] args) {Console.Write ("Please enter the shared memory common 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)) / / Note the offset {var writer = new BinaryWriter (stream) here. For (int I = 5; I < 10; iTunes +) {writer.Write (I); Console.WriteLine ("{0} position write stream: {0}", I) }} using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor (1024, 10240)) {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: I am instant messaging-status service I started!") ; Console.ReadKey ();} Thank you for your reading. The above is the content of "what is the shared memory mapping file for C#.Net communication?" after the study of this article, I believe you have a deeper understanding of what the shared memory mapping file for C#.Net communication is, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report