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();
选择建议
- 高性能需求:内存映射文件或命名管道
- 跨机器通信:WCF或套接字
- 可靠异步通信:MSMQ
- 简单临时通信:文件监视
- 与旧系统集成:COM/DCOM
每种方案都有其适用场景,应根据具体需求选择最合适的IPC技术。