I have a windows service which is communicating with a gui application via named pipes. Therefor i have a thread running waiting for the app to connect which is running fine if i do it once. But if the thread is creating a new instance of the named pipe stream server the already established connection breaks down and i get the all instances busy exception. The code fragment where the exception is thrown is this:
class PipeStreamWriter : TextWriter
{
static NamedPipeServerStream _output = null;
static StreamWriter _writer = null;
static Thread myThread = null;
public PipeStreamWriter()
{
if (myThread == null)
{
ThreadStart newThread = new ThreadStart(delegate{WaitForPipeClient();});
myThread = new Thread(newThread);
myThread.Start();
}
}
public static void WaitForPipeClient()
{
Thread.Sleep(25000);
while (true)
{
NamedPipeServerStream ps = new NamedPipeServerStream("mytestp");
ps.WaitForConnection();
_output = ps;
_writer = new StreamWriter(_output);
}
}
The exception is thrown when creating the new pipe server stream NamedPipeServerStream ps = new NamedPipeServerStream("mytestp")
the second time.
EDIT:
I found the answer and it works when the max number of server instances is specified
NamedPipeServerStream ps = new NamedPipeServerStream("mytestp",PipeDirection.Out,10);
The default value for this seems to be -1. Which leads to another but not that important question: Someone knows why it is -1 and not 1 when it behaves like beeing 1?
There are two overloads of the NamedPipeServerStream
constructor that assign a default to the maxNumberOfServerInstances
variable, namely:
public NamedPipeServerStream(String pipeName)
and
public NamedPipeServerStream(String pipeName, PipeDirection direction)
Looking at the reference source proves that this default is 1 and not -1. This explains the behavior you observed.
Possible solutions are:
use a constructor that allows you to specify the limit, and pass a value larger than 1
same as 1, and use the built-in constant NamedPipeServerStream.MaxAllowedServerInstances
to ask for the maximum number of handles the operating system will be able to allocate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With