簡化 C# 中的進程間通信:使用匿名管道的異步方法
多個 C# 進程之間的高效數據交換對於許多應用程序至關重要。 匿名管道為異步、事件驅動的進程間通信 (IPC) 提供了輕量級且強大的解決方案。
以下是如何實現匿名管道通信:
父進程:
管道創建:
<code class="language-csharp">PipeStream pipeStream = new AnonymousPipeServerStream(PipeDirection.Out);</code>
子進程啟動:將管道流作為參數傳遞給子進程。
子進程:
管道流檢索:
<code class="language-csharp">PipeStream pipeStream = (PipeStream)args[0];</code>
異步通信:
<code class="language-csharp">byte[] buffer = new byte[1024]; pipeStream.BeginRead(buffer, 0, buffer.Length, (IAsyncResult asyncResult) => { int bytesRead = pipeStream.EndRead(asyncResult); // Process the received data }, null);</code>
向父級傳輸數據:
<code class="language-csharp">byte[] data = Encoding.UTF8.GetBytes("Message from child process"); pipeStream.BeginWrite(data, 0, data.Length, (IAsyncResult asyncResult) => { pipeStream.EndWrite(asyncResult); }, null);</code>
使用匿名管道的好處:
PipeStream
類提供了一個易於使用的界面。 匿名管道為 C# 中的異步 IPC 提供了強大而高效的機制,非常適合從數據傳輸到分佈式系統的各種應用程序。它們的簡單性和低資源消耗使它們成為開發人員的寶貴資產。
以上是匿名管道如何簡化 C# 中的非同步進程間通訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!