如何对.Net中的内存映射文件使用互锁操作

Mik*_*enk 8 .net-4.0 interlocked memory-mapped-files

有没有办法对存储在内存映射文件中的值使用Interlocked.CompareExchange();Interlocked.Increment();方法?

我想实现一个多线程服务,将其数据存储在内存映射文件中,但由于它是多线程的,我需要防止冲突写入,因此我想知道Interlocked操作而不是使用显式锁.

我知道可以使用本机代码,但可以在.NET 4.0上的托管代码中完成吗?

Tra*_*den 6

好的,你就是这样做的!我们必须弄清楚这一点,我想我们可以回馈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)); 
    }
}
Run Code Online (Sandbox Code Playgroud)

这确实有效,并且适用于多个流程!永远享受一个很好的挑战!