

You should get one Console that notifies every one second that the value was updated and the other Console (the reader) should print every one second the latest value. Run both apps, first the writer, then the reader. The main advantage of using Mutex is that it can synchronize a critical region among multiple processes. Notice how we used a Mutex in both applications to synchronize the access to the MMF. It’s very similar to the writer process, just that it reads the data and writes the id and value to the Console every one second. Using (var accessor = mmf.CreateViewAccessor())Ĭonsole.WriteLine($"Updated Value to: ")

Using (var mmf = MemoryMappedFile.CreateOrOpen("MyMMF", Marshal.SizeOf(data))) Var mutex = new Mutex(false, "MmfMutex") One process will update that value every second, while the other will just read and display the value in the Console. We will have a struct with a Value and Id fields. Let’s create two Console Applications in order to have two processes and share some data between them. In order to write reference types we need to serialize the data to a file on disk. Also, we can only write value types directly to a MMF. We must implement a mechanism to avoid race conditions. A common mistake is to assume that we don’t need to synchronize the access to the file. The name must be established by the process that creates the file. Multiple processes can read and write on the same file by using the same name. It’s also important the fact that they are entirely managed by the operating system and all the processing is done directly against memory. The main advantage we gain by using memory mapped files is the performance of the write and read operations compared to a normal file. MMF is a common technique used for Inter Process Communication.Īnother great advantage of MMF is that we can create views to map specific parts of the file, so we don’t need to have the entire file in memory.

The file is created by a process and can (but not necessarily) persists after the process ends. It allows to map a file to virtual memory, so any operation over that memory will be reflected to the file. A Memory Mapped File is a low level feature provided by the operating system. Net 4.0 Microsoft introduced a mechanism to work with Memory Mapped Files (MMF) on the System.IO.MemoryMappedFiles namespace.
