marek
marek

Reputation: 279

NamedPipeServerStream and WaitForConnection method

What bugs me when working with class NamedPipeServerStream is that for every incoming connection I need to create new object and call it's method WaitForConnection.

What I want to do is to create one NamedPipeServerStream object, and then repeatedly in a while loop call aforementioned method, like that:

NamedPipeServerStream s2;
using (s2 = new NamedPipeServerStream("pipe_name", PipeDirection.InOut)) {
    while(true) {
        ss2.WaitForConnection();
        //do something here
    }
}

But when I do this, I get message

Stream has been disconnected.

Any advice?

Upvotes: 4

Views: 5926

Answers (1)

Chris Dickson
Chris Dickson

Reputation: 12135

If you want to use the NamedPipeServerStream you need to work with the programming model it gives you, which is like it is because it is wrapping an underlying Windows handle to a named pipe kernel object. You can't use it like you are trying to, because that's not how named pipe handles work.

If you really want to deal with connections one-at-a-time on a single thread, turn your loop inside out:

while (true)
{
  using (NamedPipeServerStream ss2 = new NamedPipeServerStream("pipe_name", PipeDirection.InOut)
  {
    ss2.WaitForConnection();
    // Stuff here
  }
}  

More likely, you want a multi-threaded pipe server which handles connections in parallel. If so, there are various ways - a search of other SO questions will turn up several patterns, for example here or here.

Upvotes: 9

Related Questions