目录
多个进程之间,通过操作未映射到磁盘上现有文件的内存映射文件,可以实现数据共享和类似进程间通讯的功能。以下示例展示了使用三个独立进程,先各自将布尔值写入内存映射文件,然后再由其中一个全部读取出来的功能;示例代码主要来自微软官方教程。
using System.IO.MemoryMappedFiles;
Console.WriteLine("我是独立进程A");
using MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test_mem_map_file", 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();
Console.WriteLine("请启动进程 B 并按下确认键以继续运行.");
Console.ReadLine();
Console.WriteLine("请启动进程 C 并按下确认键以继续运行.");
Console.ReadLine();
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
BinaryReader reader = new BinaryReader(stream);
Console.WriteLine("进程 A 写入的内容: {0}", reader.ReadBoolean());
Console.WriteLine("进程 B 写入的内容: {0}", reader.ReadBoolean());
Console.WriteLine("进程 C 写入的内容: {0}", reader.ReadBoolean());
}
mutex.ReleaseMutex();
Console.ReadLine();
using System.IO.MemoryMappedFiles;
Console.WriteLine("我是独立进程B");
try
{
using MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("test_mem_map_file");
Mutex mutex = Mutex.OpenExisting("testmapmutex");
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream(1, 0))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(0);
}
mutex.ReleaseMutex();
}
catch (FileNotFoundException)
{
Console.WriteLine("内存映射文件不存在. 请先运行进程A.");
}
using System.IO.MemoryMappedFiles;
Console.WriteLine("我是独立进程C");
try
{
using MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("test_mem_map_file");
Mutex mutex = Mutex.OpenExisting("testmapmutex");
mutex.WaitOne();
using (MemoryMappedViewStream stream = mmf.CreateViewStream(2, 0))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(0);
}
mutex.ReleaseMutex();
}
catch (FileNotFoundException)
{
Console.WriteLine("内存映射文件不存在. 请先运行进程A,再运行进程B.");
}
总的来说,一番体验下来,采用内存映射文件来做进程间的资源共享或状态同步还是很简便的。