C# Console Application: Inter-Process Communication with Named Pipes
Named pipes provide a robust and efficient method for inter-process communication (IPC). This example demonstrates a C# console application using named pipes to exchange messages between two processes.
Application Structure
We'll build two console applications: Application A and Application B. Application A initiates communication, sending a message to Application B, which responds accordingly.
Server (Application B)
NamedPipeServerStream
.WaitForConnection
.StreamReader
and StreamWriter
establish communication channels for message reading and writing.Server Code Example:
<code class="language-csharp">Task.Factory.StartNew(() => { using (var server = new NamedPipeServerStream("MyPipe")) { server.WaitForConnection(); using (var reader = new StreamReader(server)) using (var writer = new StreamWriter(server)) { while (true) { string message = reader.ReadLine(); if (string.IsNullOrEmpty(message)) break; //Handle potential termination string reversedMessage = new string(message.Reverse().ToArray()); writer.WriteLine(reversedMessage); writer.Flush(); } } } });</code>
Client (Application A)
NamedPipeClientStream
.Client Code Example:
<code class="language-csharp">using (var client = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut)) { client.Connect(); using (var reader = new StreamReader(client)) using (var writer = new StreamWriter(client)) { while (true) { Console.WriteLine("Enter message (or leave blank to exit):"); string input = Console.ReadLine(); if (string.IsNullOrEmpty(input)) break; writer.WriteLine(input); writer.Flush(); Console.WriteLine($"Received: {reader.ReadLine()}"); } } }</code>
Communication Process
Application A connects to the named pipe server initiated by Application B. Messages are exchanged through their respective channels. For instance, if Application A sends "Hello World", Application B reverses it to "dlroW olleH" and sends it back. Application A displays this reversed message. The loop continues until Application A sends an empty message to signal termination.
The above is the detailed content of How Can Named Pipes Facilitate Inter-Process Communication in a C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!