远程关闭后保持管道打开的最佳方法

时间:2009-11-06 18:15:08

标签: c# .net pipe named-pipes

使用this tutorial我想出了下面的代码。我的客户经常运行。它通过点击激活,并且可能在某些情况下同时启动两次。我担心一个客户端可能会关闭而另一个客户端打开导致管道在那么短的几毫秒内关闭。什么是保持管道畅通的最佳方法?

    static public void ThreadStartServer()
    {
        while (true)
        {
            using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("mytestpipe"))
            {
                Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());

                pipeStream.WaitForConnection();
                Console.WriteLine("[Server] Pipe connection established");

                using (StreamReader sr = new StreamReader(pipeStream))
                {
                    string temp;
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine("{0}: {1}", DateTime.Now, temp);
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

使管道服务器具有多线程,一个线程专用于侦听。请参阅these answers