C#进程同步之管道通信

//write

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)
                {
                }
            }
        }
    }
}
单向管道允许一端写另一段读,双向管道允许一个进程既可以读又可以向管道写数据。
http://blog.sina.com.cn/s/blog_4b3485000101827p.html


你可能感兴趣的:(C#)