C# 使用内存映射文件实现进程间通信

新建两个进程程序:

A:

cs 复制代码
 static void Main(string[] args)
 {
     // 此处的 MemoryMappedFile 实例不能使用 using 语法
     // 因为它会自动释放我们的内存映射文件,会导致进程B找不到这个映射文件而抛出异常
     MemoryMappedFile mmf = MemoryMappedFile.CreateNew("IPC_MAP", 10000);
     // 创建互斥量以协调数据的读写
     Mutex mutex = new Mutex(true, "IPC_MAP_MUTEX", out bool mutexCreated);
     using (MemoryMappedViewStream stream = mmf.CreateViewStream())
     {
         StreamWriter sw = new StreamWriter(stream);
         // 向内存映射文件种写入数据
         sw.WriteLine("This is IPC MAP TEXT");
         // 这一句是必须的,在某些情况下,如果不调用Flush 方法会造成进程B读取不到数据
         // 它的作用是立即写入数据
         // 这样在此进程释放 Mutex 的时候,进程B就能正确读取数据了
         sw.Flush();
     }
     mutex.ReleaseMutex();

     Console.ReadLine();

     mmf.Dispose();
 }

B:

cs 复制代码
 static void Main(string[] args)
 {
     using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("IPC_MAP"))
     {
         Mutex mutex = Mutex.OpenExisting("IPC_MAP_MUTEX");
         // 等待写入完成
         mutex.WaitOne();
         using (MemoryMappedViewStream stream = mmf.CreateViewStream())
         {
             StreamReader sr = new StreamReader(stream);
             // 读取进程 A 写入的内容
             Console.WriteLine(sr.ReadLine());
         }
         mutex.ReleaseMutex();
     }

     Console.ReadLine();
 }

依次启动A、B,在B的窗口中:

代码引用自:

温故之.NET进程间通信------内存映射文件 - 知乎

那MemoryMappedFile.CreateNew是什么回事呢?

一直F12深入下去看看:

还是调用的win32的CreateFileMapping,但是多了很多封装,使用起来很方便。

关于CreateFileMapping,资源就很多了,这里不赘述。

另外,C#中很多对象是可以在进程间共享的,可以自行学习。

相关推荐
kaikaile199520 小时前
数字全息图处理系统(C# 实现)
开发语言·c#
wearegogog1231 天前
C# .NET 文件比较工具 WinForms
开发语言·c#·.net
糖不吃1 天前
WPF值转换器
c#
Popeye-lxw1 天前
由罗技 K380 键盘 FN 键模式切换引发的血案
c#
FL16238631291 天前
C# OpenCvSharp 基于霍夫变换直线检测的文本图像倾斜校正文本图像倾斜校
开发语言·c#
aini_lovee1 天前
C# 快递单打印系统(万能套打系统)
开发语言·c#
白菜上路1 天前
C# Serilog.AspNetCore基本使用
c#·serilog
小白不白1111 天前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10111 天前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather1 天前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel