2

我正在尝试在两个进程之间进行通信。从 MSDN 文档中,我遇到了 MemoryMappingFile,我正在使用它进行通信。

public class SmallCommunicator : ICommunicator
    {
        int length = 10000;
        private MemoryMappedFile GetMemoryMapFile()
        {

            var security = new MemoryMappedFileSecurity();
            security.SetAccessRule(
                new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("EVERYONE", 
                    MemoryMappedFileRights.ReadWriteExecute, System.Security.AccessControl.AccessControlType.Allow));

            var mmf = MemoryMappedFile.CreateOrOpen("InterPROC", 
                            this.length, 
                            MemoryMappedFileAccess.ReadWriteExecute, 
                            MemoryMappedFileOptions.DelayAllocatePages, 
                            security, 
                            HandleInheritability.Inheritable);

            return mmf;

        }

        #region ICommunicator Members

        public T ReadEntry<T>(int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            using (mf)
            {
                int dsize = Marshal.SizeOf(typeof(T));
                T dData;
                int offset = dsize * index;
                using (var accessor = mf.CreateViewAccessor(0, length))
                {
                    accessor.Read(offset, out dData);
                    return dData;
                }
            }
        }

        public void WriteEntry<T>(T dData, int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            using (mf)
            {
                int dsize = Marshal.SizeOf(typeof(T));
                int offset = dsize * index;
                using (var accessor = mf.CreateViewAccessor(0, this.length))
                {
                    accessor.Write(offset, ref dData);
                }
            }
        }

        #endregion
    }

谁能告诉我为什么这段代码不起作用。与磁盘文件一起使用时相同的代码可以工作。

在连续读取和写入数据时,数据似乎丢失了。我错过了什么吗?

4

1 回答 1

0

嗯,我有问题。

似乎 MemoryMappedFile 需要保持未处理,以便由窗口自动处理。所以当我读或写的时候,我不能包括

使用(MF)

堵塞。这将删除共享内存。所以实际的代码应该是:

 public void WriteEntry<T>(T dData, int index) where T : struct
        {
            var mf = this.GetMemoryMapFile();
            int dsize = Marshal.SizeOf(typeof(T));
            int offset = dsize * index;
            using (var accessor = mf.CreateViewAccessor(0, this.length))
            {
                accessor.Write(offset, ref dData);
            }
        }

不管怎么说,还是要谢谢你。

于 2012-02-14T02:49:24.770 回答