9

メモリ マップト ファイルに格納されている値に対して メソッドInterlocked.CompareExchange();とメソッドを使用する方法はありますか?Interlocked.Increment();

データをメモリ マップ ファイルに格納するマルチスレッド サービスを実装したいのですが、マルチスレッドであるため書き込みの競合を防ぐ必要があるため、明示的なロックを使用するのではなく、インターロック操作について疑問に思います。

ネイティブ コードで可能であることはわかっていますが、.NET 4.0 のマネージ コードで実行できますか?

4

2 に答える 2

7

OK、これがあなたのやり方です!これを解決する必要があり、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)); 
    }
}

これは機能し、複数のプロセスで機能します! 常に良い挑戦を楽しんでください!

于 2012-08-24T20:54:47.633 に答える