views:

91

answers:

1

Hi i have a couple of question about using named pipes.

Firstly, when trying to setup a pipe server, i have noticed that if i use the code below.. at the end of the first client connect the server becomes unavailable UNLESS i wrap the whole thing in a while (true) block. Have i done this correct? or is each server only supposed to be active once and then die?

using (NamedPipeServerStream pipeServerStream = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, transmissionMode))
{
    pipeServerStream.WaitForConnection();

    using (StreamReader sr = new StreamReader(pipeServerStream))
    {
     string message = null;

     do
     {
      message = sr.ReadLine();
      OnPipeCommunicationHandler(new IPCData() { Data = message });
     }
     while (message != null);
    }
}

Secondly, i have also had to spin off the server on its own thread - If i dont do this my application wont become available. Is this normal? have i done this correctly? I thought i read somewhere that under the hood the namedpipeserverstream creates its own thread for itself but i cant see that that is the case..

Thanks!

+1  A: 

Yes, for named pipes you need to create a new instance of the server for the next client to be able to connect. What is normally done (in synchronous programming at least) is you wait for a connection then spawn a new thread to handle the client, with the original thread looping back to create a new server.

As for threading, well even if the object creates a thread behind the scenes (which I doubt) it doesn't get around the fact that the code you have written is synchronous and thus would need to be in its own thread anyway.

tyranid