我正在尝试在两个进程之间进行通信。从 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
}
谁能告诉我为什么这段代码不起作用。与磁盘文件一起使用时相同的代码可以工作。
在连续读取和写入数据时,数据似乎丢失了。我错过了什么吗?