Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 887
Sam Rueby Avatar asked Jan 11 '12 14:01

Sam Rueby


2 Answers

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.

like image 151
RandomEngy Avatar answered Sep 18 '22 11:09

RandomEngy


It is an odd argument, you'll find a bit more info about it in the documentation for the underlying Windows API function (CreateNamedPipe). Pipes use a very precious resource for the pipe buffers, they are allocated from the non-paged kernel memory pool. I think this argument helps Windows optimize the usage of the pool. Exactly how that's done is hopelessly undocumented.

The perfect number for a single service that accepts multiple client connections is 1. You'd only increase it if you want to run multiple services that all do the same job. That's pretty rare.

like image 31
Hans Passant Avatar answered Sep 20 '22 11:09

Hans Passant