user34537
user34537

Reputation:

Best way to keep a pipe open after a remote close

Using this tutorial i came up with the code below. My client is ran frequently. Its activated via clicks and possibly can be launched twice at the same moment in certain circumstance. I am worried one client may close while another client opens which causes the pipe to be closed in that slim few milliseconds. Whats the best way to keep the pipe open?

    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);
                    }
                }
            }
        }

Upvotes: 2

Views: 2589

Answers (1)

Chris Dickson
Chris Dickson

Reputation: 12135

Make your pipe server multi-threaded, with one thread dedicated to listening. See these answers:

Upvotes: 1

Related Questions