我引用了msdn share memory
找到CreateViewStream,现在我想创建int
在内存中使用MemoryMappedViewAccessor
// Process A:
static void Main(string[] args)
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew("testmap", 10000))
{
bool mutexCreated;
Mutex mutex = new Mutex(true, "testmapmutex", out mutexCreated);
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(1);
}
mutex.ReleaseMutex();
// Read Int
MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor();
// For Process B Read
accessor.Write(499, 41);
// For Process B Read
accessor.Write(500, 42);
// For Process C Read
accessor.Write(501, 43);
accessor.Dispose();
Console.WriteLine("Start Process B and press ENTER to continue.");
Console.ReadLine();
Console.WriteLine("Start Process C and press ENTER to continue.");
Console.ReadLine();
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader reader = new BinaryReader(stream);
MemoryMappedViewAccessor access = mmf.CreateViewAccessor();
Console.WriteLine("Process A says: {0} ", reader.ReadBoolean());
Console.WriteLine("Process B says: {0} ", reader.ReadBoolean());
Console.WriteLine("Process C says: {0} ", reader.ReadBoolean());
Console.WriteLine("Process A Int:{0}", access.ReadInt32(499));
Console.WriteLine("Process B Int:{0}", access.ReadInt32(500));
Console.WriteLine("Process C Int:{0}", access.ReadInt32(501));
access.Dispose();
}
mutex.ReleaseMutex();
mmf.Dispose();
}
Console.Read();
}
但结果如下
流程A说:是的 流程B说:错误 流程C说:错误 Process A Int:2828841 过程B Int:11050 Process C Int:43
任何人都可以告诉我这个问题吗?
为什么结果处理A,B
不是41和42
答案 0 :(得分:0)
查找此代码
// For Process B Read
accessor.Write(499, 41);
// For Process B Read
accessor.Write(503, 42);
// For Process C Read
accessor.Write(507, 43);
Console.WriteLine("Process A Int:{0}", access.ReadInt32(499));
Console.WriteLine("Process B Int:{0}", access.ReadInt32(503));
Console.WriteLine("Process C Int:{0}", access.ReadInt32(507));
然后结果是
处理A Int:41 过程B Int:42 Process C Int:43
或查找此代码
Console.WriteLine("Process A Int:{0}", access.ReadByte(499));
Console.WriteLine("Process B Int:{0}", access.ReadByte(500));
Console.WriteLine("Process C Int:{0}", access.ReadByte(501));
有相同的结果
感谢@Hans Passant