A little over a year ago, I started a project on Codeplex which contained managed implementations for Memory-Mapped Files, Mail slots and “Shared Memory”. The project is called: Inter-process (IPC) Communication Library.
From CodePlex:
IPCLibrary - Project Description
A class library providing managed code implementation of mailslots, memory mapped files, and shared memory. The library includes the following public objects:
Mailslot - Mailslot server implementation
Mailslot Client - Mailslot client implementation
MemoryMappedFile - Memory mapped files backed by files or paging file
SharedMemory - Managed access to shared dll data segments
Well, Framework 4.0 contains a new namespace: System.IO.MemoryMappedFile.
Comparing Implementations
Microsoft did a better job at the implementation than I did, which is not surprising. Some notes on the two implementations:
- Microsoft used static factory methods; I used overloaded constructors. Similar in numbers and parameters, however.
- Microsoft provides classes for managing security and file access permissions. Me?, nothing in that area. ;-)
- We both used helper classes for reading/writing data, derived from Stream. (MemoryMappedViewStream vs MemoryMappedFileStream in my case, although MS introduced a new base stream class “UnmanagedMemoryStream”).
- Microsoft provides direct access via MemoryMappedViewAccessor, my implementation contained ReadBytes() and WriteBytes() methods directly on the MemoryMappedFile class.
- Both implementations are thread-safe. (It’s IPC after all!). To be more accurate, I am fairly sure Microsoft’s implementation is thread-safe and pretty sure mine is. Both are designed to be thread-safe. :-)
- My implementation/library also contained a SharedMemory class – a “cousin” of MemoryMappedFile - for use with shared data in unmanaged DLLs. I need to look further, but I believe the new classes for accessing unmanaged memory provide similar features.
I am quite glad the new System.IO.MemoryMappedFile namespace was added to the framework. Very similar to System.IO.Pipes and System.IO.Ports, Microsoft is filling in the missing pieces of managed code. Do we need mailslots? I think not. I only put that in my IPCLibrary for completeness (Microsoft had already done pipes in framework 2.0), and I don’t believe mailslots ever are used these days. Someone from Microsoft on the CLR team once answered the question: “Why don’t you put XXX into the framework” with a very good answer. There is no need to implement something that will not be used. However, the new MemoryMappedFiles namespace, while not for everyone, is a very welcome addition to the framework for those who need it.