How to use blocked file operations with memory mapping in .Net

Is it possible to use Interlocked.CompareExchange(); methods Interlocked.CompareExchange(); and Interlocked.Increment(); for values ​​stored in a memory mapped file?

I would like to implement a multi-threaded service that will store its data in a memory-mapped file, but since it is multi-threaded, I need to prevent conflicting entries, so I am wondering about locking operations, rather than using explicit locks.

I know that this is possible using native code, but can this be done in managed code on .NET 4.0?

+7
source share
1 answer

Well, here's how you do it! We had to understand this, and I decided that we would return to stackoverflow!

 class Program { internal static class Win32Stuff { [DllImport("kernel32.dll", SetLastError = true)] unsafe public static extern int InterlockedIncrement(int* lpAddend); } private static MemoryMappedFile _mmf; private static MemoryMappedViewStream _mmvs; unsafe static void Main(string[] args) { const int INT_OFFSET = 8; _mmf = MemoryMappedFile.CreateOrOpen("SomeName", 1024); // start at offset 8 (just for example) _mmvs = _mmf.CreateViewStream(INT_OFFSET, 4); // Gets the pointer to the MMF - we dont have to worry about it moving because its in shared memory var ptr = _mmvs.SafeMemoryMappedViewHandle.DangerousGetHandle(); // Its important to add the increment, because even though the view says it starts at an offset of 8, we found its actually the entire memory mapped file var result = Win32Stuff.InterlockedIncrement((int*)(ptr + INT_OFFSET)); } } 

It works and works in several processes! Always enjoy a good challenge!

+6
source

All Articles