C#中使用匿名管道實現高效進程間通訊
在C#中建立父子進程間的通訊時,效率至關重要。匿名管道提供了一個簡單而有效的非同步、事件驅動型通訊解決方案。
匿名管道是進程之間單向的通訊通道。它們允許異步傳輸數據,同時無需專用線程來處理不頻繁的通信。
要在C#中實作匿名管道,可以使用System.IO.Pipes
命名空間。它提供了NamedPipeClientStream
和NamedPipeServerStream
類,分別用於建立客戶端和伺服器端點。
客戶端實作
using System.IO.Pipes; using System.Threading; namespace ChildProcess { class Program { static void Main(string[] args) { // 连接到服务器管道 using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "MyPipe", PipeDirection.In)) { pipeClient.Connect(); // 启动一个线程来异步读取消息 Thread readThread = new Thread(() => ReadMessages(pipeClient)); readThread.Start(); // 持续读取消息 while (true) { // 执行其他任务 } } } static void ReadMessages(NamedPipeClientStream pipeClient) { while (true) { byte[] buffer = new byte[1024]; int bytesRead = pipeClient.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { // 处理接收到的消息 } } } } }
伺服器端實作
using System.IO.Pipes; using System.Threading.Tasks; namespace ParentProcess { class Program { static void Main(string[] args) { // 创建服务器管道 using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("MyPipe", PipeDirection.Out)) { // 等待客户端连接 pipeServer.WaitForConnection(); // 异步发送消息 Task.Run(() => WriteMessages(pipeServer)); } } static async void WriteMessages(NamedPipeServerStream pipeServer) { while (true) { // 执行其他任务 // 向管道写入消息 string message = "来自父进程的问候!"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message); await pipeServer.WriteAsync(buffer, 0, buffer.Length); } } } }
此方案提供了一種高效且輕量級的進程間通訊方法,無需專用執行緒的開銷。使用匿名管道和非同步操作可確保即時、事件驅動的通訊。
以上是匿名管如何在C#中增強有效的過程間通信?的詳細內容。更多資訊請關注PHP中文網其他相關文章!