.net/C#进程间通信技术方案总结

C# 应用进程间通信(IPC)技术方案

进程间通信(Inter-Process Communication, IPC)是不同进程之间交换数据和消息的机制。以下是C#中常用的IPC技术方案:

1. 命名管道(Named Pipes)

适用于本地机器上的进程通信,支持双向通信。

​服务端示例​​:

复制代码

csharp

复制代码
using System.IO.Pipes;

var server = new NamedPipeServerStream("MyPipe", PipeDirection.InOut);
server.WaitForConnection();

using (StreamReader reader = new StreamReader(server))
using (StreamWriter writer = new StreamWriter(server))
{
    string message = reader.ReadLine();
    Console.WriteLine($"Received: {message}");
    writer.WriteLine("Hello from server!");
    writer.Flush();
}

​客户端示例​​:

复制代码

csharp

复制代码
using System.IO.Pipes;

var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut);
client.Connect();

using (StreamReader reader = new StreamReader(client))
using (StreamWriter writer = new StreamWriter(client))
{
    writer.WriteLine("Hello from client!");
    writer.Flush();
    string response = reader.ReadLine();
    Console.WriteLine($"Server response: {response}");
}

2. 内存映射文件(Memory-Mapped Files)

允许不同进程通过共享内存进行通信。

​写入进程​​:

复制代码

csharp

复制代码
using System.IO.MemoryMappedFiles;

using (var mmf = MemoryMappedFile.CreateOrOpen("MySharedMemory", 1024))
using (var accessor = mmf.CreateViewAccessor())
{
    byte[] message = Encoding.UTF8.GetBytes("Hello from Process 1!");
    accessor.WriteArray(0, message, 0, message.Length);
}

​读取进程​​:

复制代码

csharp

复制代码
using (var mmf = MemoryMappedFile.OpenExisting("MySharedMemory"))
using (var accessor = mmf.CreateViewAccessor())
{
    byte[] buffer = new byte[1024];
    accessor.ReadArray(0, buffer, 0, buffer.Length);
    string message = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
    Console.WriteLine($"Received: {message}");
}

3. WCF (Windows Communication Foundation)

.NET框架提供的强大通信框架,支持多种协议。

​服务端​​:

复制代码

csharp

复制代码
using System.ServiceModel;

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string GetMessage();
}

public class MyService : IMyService
{
    public string GetMessage() => "Hello from WCF service!";
}

var host = new ServiceHost(typeof(MyService), new Uri("net.pipe://localhost"));
host.AddServiceEndpoint(typeof(IMyService), new NetNamedPipeBinding(), "MyService");
host.Open();

​客户端​​:

复制代码

csharp

复制代码
var factory = new ChannelFactory<IMyService>(
    new NetNamedPipeBinding(),
    new EndpointAddress("net.pipe://localhost/MyService"));
    
IMyService proxy = factory.CreateChannel();
string message = proxy.GetMessage();
Console.WriteLine($"Service response: {message}");

4. 套接字(Sockets)

适用于网络通信,也可用于本地进程间通信。

​TCP服务端​​:

复制代码

csharp

复制代码
var listener = new TcpListener(IPAddress.Loopback, 12345);
listener.Start();

var client = listener.AcceptTcpClient();
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
    string request = reader.ReadLine();
    writer.WriteLine($"Echo: {request}");
    writer.Flush();
}

​TCP客户端​​:

复制代码

csharp

复制代码
var client = new TcpClient("localhost", 12345);
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
    writer.WriteLine("Hello from client!");
    writer.Flush();
    string response = reader.ReadLine();
    Console.WriteLine(response);
}

5. 消息队列(MSMQ)

适用于异步、可靠的进程间通信。

​发送消息​​:

复制代码

csharp

复制代码
using System.Messaging;

if (!MessageQueue.Exists(@".\Private$\MyQueue"))
    MessageQueue.Create(@".\Private$\MyQueue");

var queue = new MessageQueue(@".\Private$\MyQueue");
queue.Send("Hello from sender process!", "Test Message");

​接收消息​​:

复制代码

csharp

复制代码
var queue = new MessageQueue(@".\Private$\MyQueue");
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });

Message message = queue.Receive();
Console.WriteLine($"Received: {message.Body}");

6. 文件监视(File System Watcher)

通过共享文件和文件系统事件进行通信。

​写入进程​​:

复制代码

csharp

复制代码
File.WriteAllText("shared.txt", "Hello from Process 1!");

​监视进程​​:

复制代码

csharp

复制代码
var watcher = new FileSystemWatcher
{
    Path = Directory.GetCurrentDirectory(),
    Filter = "shared.txt",
    NotifyFilter = NotifyFilters.LastWrite
};

watcher.Changed += (s, e) => 
{
    string content = File.ReadAllText(e.FullPath);
    Console.WriteLine($"File changed: {content}");
};

watcher.EnableRaisingEvents = true;

7. COM/DCOM

适用于与遗留系统或非.NET应用程序通信。

​COM服务器示例​​:

复制代码

csharp

复制代码
[ComVisible(true)]
[Guid("...")]
[ClassInterface(ClassInterfaceType.AutoDual)]
public class MyComServer
{
    public string GetMessage() => "Hello from COM server!";
}

​COM客户端​​:

复制代码

csharp

复制代码
Type comType = Type.GetTypeFromProgID("MyComServer");
dynamic comObject = Activator.CreateInstance(comType);
string message = comObject.GetMessage();

选择建议

  1. ​高性能需求​:内存映射文件或命名管道
  2. ​跨机器通信​:WCF或套接字
  3. ​可靠异步通信​:MSMQ
  4. ​简单临时通信​:文件监视
  5. ​与旧系统集成​:COM/DCOM

每种方案都有其适用场景,应根据具体需求选择最合适的IPC技术。

相关推荐
渡我白衣12 分钟前
链接的迷雾:odr、弱符号与静态库的三国杀
android·java·开发语言·c++·人工智能·深度学习·神经网络
A.A呐13 分钟前
【QT第三章】常用控件1
开发语言·c++·笔记·qt
Bony-14 分钟前
Go语言并发编程完全指南-进阶版
开发语言·后端·golang
007php00725 分钟前
大厂深度面试相关文章:深入探讨底层原理与高性能优化
java·开发语言·git·python·面试·职场和发展·性能优化
say_fall1 小时前
C语言容易忽略的小知识点(1)
c语言·开发语言
津津有味道1 小时前
Ntag 424 DNA写入URI网址配置开启动态UID计数器镜像C#源码
c#·uri·ndef·424dna·动态uid·计数器镜像
不会编程的小寒1 小时前
C++初始继承,继承中构造、析构顺序
开发语言·python
运维管理1 小时前
Linux系统笔记--Base
开发语言·php
全栈软件开发2 小时前
最新版T5友价互站网源码商城PHP源码交易平台 完整带手机版源码网系统源码
android·开发语言·php
Mos_x2 小时前
关于我们的python日记本
开发语言·python