Search code examples
.netwindows-servicesnamed-pipes

What is the purpose of maxNumberOfServerInstances in the NamedPipeServerStream class?


Currently writing a Windows service in .NET and I'm using named pipes to have other processes communicate with my service. In the more complicated constructors of NamedPipeServerStream, there's a parameter with a descriptive name of maxNumberOfServerInstances. Awesome. But what does that mean?

MSDN's documentation is also helpful at explaining:

The maximum number of server instances that share the same name.

Okay. That still doesn't really tell me what this does for me, or how I utilize it. It would make sense to be if NamedPipeServerStream also accepted some delegate for "run this code when I receive a connection", so then each "Server instance" would then run that code. But that's not the case.


Solution

  • In practice it limits the number of NamedPipeServerStream instances you can create for the same pipe name. This will throw System.IO.IOException: All pipe instances are busy.:

    var pipeStreamA = new NamedPipeServerStream("mypipe1", PipeDirection.InOut, 1);
    var pipeStreamB = new NamedPipeServerStream("mypipe1", PipeDirection.InOut, 1);
    

    If you change to -1 or 2, then it won't throw an exception. Also, it only respects the value on the first instance you create. If you specify 1 on the first call and 2 on the second, it will still throw an exception.

    It's probably a good idea to set this to the maximum number of simultaneous servers that you expect to try to run, because as Hans mentioned, it may be using the number as a hint for the amount of resources to allocate.