.Net文件映射的问题

时间:2014-01-21 00:09:32

标签: c# .net multithreading multiprocessing file-mapping

有两个过程:

  1. Win32,C ++ - writer
  2. .Net 4.5,C# - reader
  3. 第一个进程创建缓冲区并为第二个进程共享。

    • (int)(buffer + 0) - 直到你可以写。
    • (int)(缓冲区+4) - 直到你可以阅读。
    • ... - block [size_mess] [mess]

    记录圆形度,即当你到达缓冲区的末尾时,寻找到开头。

    在某些时候发生错误。

    1进程等待读取数据。 2进程读取块,但读取旧数据(在上一次传递期间记录)。

    尝试使用MemoryMappedViewAccessor,MemoryMappedViewStream ......没有效果

    可能因.NET而延迟?

    unsafe public void LoadFromMemory(string name)
    {
        const UInt32 capacity = 1200;
        const UInt32 maxsize = 1024;
        MemoryMappedFile mf = MemoryMappedFile.OpenExisting(name,MemoryMappedFileRights.FullControl);
        MemoryMappedViewStream stream = mf.CreateViewStream(0, capacity,MemoryMappedFileAccess.ReadWrite);
        BinaryReader reader = new BinaryReader(stream);
        byte* bytePtr = null;
        stream.SafeMemoryMappedViewHandle.AcquirePointer(ref bytePtr);
    
        int size = 0;
        long pos_begin = 0x10;
    
        long pos_max = Interlocked.CompareExchange(ref *((int*)(bytePtr + 4)), 0, 0);
        while (<work>)
        {
            while (pos_begin >= pos_max)
            {
                pos_max = Interlocked.CompareExchange(ref *((int*)(bytePtr+4)), 0, 0);
            }
            size = (bytePtr[pos_begin + 1] << 8) + bytePtr[pos_begin];
    
            stream.Seek(pos_begin + 2, SeekOrigin.Begin);
            work(reader);
    
    //if here put a breakpoint, 
    //in time of error  size ! = Watch.bytePtr[pos_begin] and all other data
    
            if (pos_begin + size > maxsize) pos_begin = 0x10; // to beginning
            else pos_begin += size;
            Interlocked.Exchange(ref *((int*)bytePtr), (int)pos_begin); // for first process
        }
    }
    

0 个答案:

没有答案