
C# で匿名パイプを使用して効率的なプロセス間通信を実現する
C# で親プロセスと子プロセス間の通信を確立する場合、効率が非常に重要です。匿名パイプは、シンプルかつ効果的な非同期のイベント駆動型通信ソリューションを提供します。
匿名パイプはプロセス間の一方向通信チャネルです。これにより、まれな通信を処理するための専用スレッドの必要性を排除しながら、データを非同期で転送できるようになります。
C# で匿名パイプを実装するには、System.IO.Pipes
名前空間を使用できます。これは、クライアントとサーバーのエンドポイントをそれぞれ作成するための NamedPipeClientStream
クラスと NamedPipeServerStream
クラスを提供します。
クライアント実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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)
{
}
}
}
}
}
|
ログイン後にコピー
サーバー側の実装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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 中国語 Web サイトの他の関連記事を参照してください。