Pipelines are used to communicate between processes on the same machine or between different machines in the same network. You can use anonymous pipelines and named pipelines in. net. Pipeline-related classes are in the system. Io. Pipes namespace .. The essence of pipelines in. NET is the encapsulation of MPs queue-related functions in Windows APIs.
Use an anonymous pipeline to communicate with Parent and Child processes:
An anonymous pipeline is a type of half-duplex communication. The so-called half-duplex communication means that only one end of the communication can be written to the other end for readability. An anonymous pipeline can only be used on the same machine, it cannot be used across networks on different machines.
As the name suggests, an anonymous pipeline is an unnamed pipeline. It is often used for communication between parent and child processes. When a parent process creates a child process, it must pass the handle of an anonymous pipeline to the child process as a string, let's take a look at the example:
The parent process creates an anonuspuspipeserverstream, then starts the process, and passes the handle of the created anonymouspuspipeserverstream to the child process as a parameter. The following code:
Process = new process (); process. startinfo. filename = "child.exe"; // create an anonymous pipeline stream instance, using (anonymouspipeserverstream pipestream = new anonymouspuspipeserverstream (pipedirection. out, handleinheritability. inheritable) {// pass the handle to the sub-process. startinfo. arguments = pipestream. getclienthandleasstring (); process. startinfo. useshellexecute = false; process. start (); // destroy the client handle of the sub-process? Pipestream. disposelocalcopyofclienthandle (); Using (streamwriter Sw = new streamwriter (pipestream) {SW. autoflush = true; // write the content SW to the anonymous pipeline. writeline (console. readline () ;}} process. waitforexit (); process. close ();
The sub-process declares an anonymouspipeclientstream instance and reads the content from the instance. The following code:
using (StreamReader sr = new StreamReader( new AnonymousPipeClientStream(PipeDirection.In, args[0]))) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine("Echo: {0}", line); }}
This program must be executed in the CMD command line. Otherwise, the execution result is invisible. The execution result is to input a line of text in the parent process, and the child process outputs ECHO: text.
Named Pipe:
The named pipeline is more powerful than the anonymous pipeline, and can implement duplex communication between processes (that is, the two processes that communicate can both read and write ); the named pipe can also communicate with different machines across networks. You can create multiple namedpipeserverstream instances in multiple threads to serve multiple clients. In addition, the Named Pipe supports message transmission, so that the client can read messages of any length without knowing the message length.
The following is the server process code:
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("testpipe")){ pipeStream.WaitForConnection(); using (StreamWriter writer = new StreamWriter(pipeStream)) { writer.AutoFlush = true; string temp; while ((temp = Console.ReadLine()) != "stop") { writer.WriteLine(temp); } }}
The following client process code:
Static void main (string [] ARGs) {using (namedpipeclientstream pipestream = new namedpipeclientstream ("testpipe") {pipestream. connect (); // using (streamreader RDR = new streamreader (pipestream) {string temp; while (temp = RDR. readline ())! = "Stop") {console. writeline ("{0 }:{ 1}", datetime. Now, temp) ;}} console. Read ();}
The above code execution result is the text input by the server, and the client displays the time and content of the received text. As mentioned above, the named pipe is fully-duplex communication, so you can also let the client write the content, while the Server accepts the content, the code is similar.
Message transmission-based named pipeline:
A message-based named pipeline can transmit an indefinite amount of content without passing the content length or Terminator. We input a text segment to the pipeline for non-message-based transmission, the writeline method uses the carriage return line break as the terminator to transmit information, and the other end of the pipeline uses the Readline method to read the carriage return line break as a flag for the End of message transmission; this is not required when message-based transmission is used. Example:
Server code:
static void Main(string[] args){ UTF8Encoding encoding = new UTF8Encoding(); string message1 = "Named Pipe Message Example."; string message2 = "Another Named Pipe Message Example."; Byte[] bytes; using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("messagepipe", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None)) { pipeStream.WaitForConnection(); // Let’s send two messages. bytes = encoding.GetBytes(message1); pipeStream.Write(bytes, 0, bytes.Length); bytes = encoding.GetBytes(message2); pipeStream.Write(bytes, 0, bytes.Length); }}
Client code:
static void Main(string[] args){ Decoder decoder = Encoding.UTF8.GetDecoder(); Byte[] bytes = new Byte[10]; Char[] chars = new Char[10]; using (NamedPipeClientStream pipeStream = new NamedPipeClientStream("messagepipe")) { pipeStream.Connect(); pipeStream.ReadMode = PipeTransmissionMode.Message; int numBytes; do { string message = ""; do { numBytes = pipeStream.Read(bytes, 0, bytes.Length); int numChars = decoder.GetChars(bytes, 0, numBytes, chars, 0); message += new String(chars, 0, numChars); } while (!pipeStream.IsMessageComplete); decoder.Reset(); Console.WriteLine(message); } while (numBytes != 0); }}
The pipetransmissionmode must be set to pipetransmissionmode. Message when constructing namedpipeserverstream based on message transmission information. The readmode attribute of namedpipeclientstream must be set to pipetransmissionmode when receiving the message from the client.
The above is only a simple example of pipeline use. When using it, you must also consider multi-threaded Access Control and Permission control.
Http://blogs.msdn.com/ B /bclteam/archive/2006/12/07/introducing-pipes-justin-van-patten.aspx according to my own views on the original made some changes.
Source code download
Related essays:
. Net: Windows File Operations in system. Io
. Net series: stream of system. Io
System. Io memory ing file shared memory
System. Io uses pipelines for inter-process communication (using system. Io. Pipes)
System. Io series: multiple threads in the LAN use named pipes to communicate instances between processes