Introduction
MemoryMappedFile is an interesting new class in version 4.0 of the .NET Framework which resides in the System.IO.MemoryMappedFiles namespace.
A memory-mapped file is a feature of the Windows operating system which allows memory to be shared between two or more processes running on the same machine. It requires much less overhead than other methods of inter-process communication such as remoting or WCF.
It also allows fast random access to that memory - much faster than file streams or pipes which are optimized for sequential access.
Whilst it was possible in earlier versions of .NET to create and access memory-mapped files by calling Windows API functions, this was rather a tortuous process and the new class wraps the native functions in an easy-to-use and intuitive way.
Example of use
Suppose we want to create a 1,000-byte file and share it with another process. The following program (program1.cs) does this:
- using System;
- using System.IO.MemoryMappedFiles;
- class Program1
- {
- static void Main()
- {
- // create a memory-mapped file of length 1000 bytes and give it a 'map name' of 'test'
- MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", 1000);
- // write an integer value of 42 to this file at position 500
- MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
- accessor.Write(500, 42);
- Console.WriteLine("Memory-mapped file created!");
- Console.ReadLine(); // pause till enter key is pressed
- // dispose of the memory-mapped file object and its accessor
- accessor.Dispose();
- mmf.Dispose();
- }
- }

Gowtham RajamanickamPosted Mar 13, 2015, 1:54 AM
Good article for learners....