当前位置:首页 > Windows程序 > 正文

C#进程同步之管道通信

2021-03-28 Windows程序

using System; using System.IO; using System.IO.Pipes; using System.Security.Principal; using System.Threading; namespace memoryWrite { class Program { static void Main(string[] args) { try { NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream(".", "closePipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); namedPipeClientStream.Connect(); StreamWriter sw = new StreamWriter(namedPipeClientStream); sw.WriteLine("Exit"); sw.Flush(); Thread.Sleep(1000); sw.Close(); } catch (Exception ex) { } } } }

//read

using System; using System.IO; using System.IO.Pipes; using System.Threading; namespace memoryRead { class Program { static void Main(string[] args) { while (true) { try { NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream("closePipe", PipeDirection.InOut, 2); namedPipeServerStream.WaitForConnection(); StreamReader sr = new StreamReader(namedPipeServerStream); string recData = sr.ReadLine(); if (recData == "Exit") { Console.Write("success"); } Thread.Sleep(1000); sr.Close(); } catch (Exception ex) { } } } } } 单向管道允许一端写另一段读,,双向管道允许一个进程既可以读又可以向管道写数据。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/68893.html