Dot-Net-4.0

如何對 .Net 中的記憶體映射文件使用互鎖操作

  • June 4, 2018

有沒有辦法對儲存在記憶體映射文件中的值使用Interlocked.CompareExchange();and方法?Interlocked.Increment();

我想實現一個多執行緒服務,它將其數據儲存在記憶體映射文件中,但由於它是多執行緒的,我需要防止寫入衝突,因此我想知道互鎖操作而不是使用顯式鎖。

我知道可以使用本機程式碼,但是可以在 .NET 4.0 上的託管程式碼中完成嗎?

好的,這就是你的做法!我們必須弄清楚這一點,我認為我們可以回饋給 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)); 
   }
}

這確實有效,並且可以跨多個程序工作!永遠享受一個好的挑戰!

引用自:https://stackoverflow.com/questions/7732042