Async NamedPipes in case of multiple pipe server instances

馋奶兔 提交于 2019-12-06 13:56:54

So finally I've found a solution (don't sure it's optimal - but it's working). It is based on using NamedPipeClientStream.NumberOfServerInstances.

public void Send(string SendStr, string PipeName, int TimeOut = 1000)
{
    try
    {
        NamedPipeClientStream pipeStream = new NamedPipeClientStream
          (".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous);

        // The connect function will indefinitely wait for the pipe to become available
        // If that is not acceptable specify a maximum waiting time (in ms)
        pipeStream.Connect(TimeOut); 

        int _serverCount = pipeStream.NumberOfServerInstances; 

        byte[] _buffer = Encoding.UTF8.GetBytes(SendStr);
        pipeStream.BeginWrite(_buffer, 0, _buffer.Length, new AsyncCallback(AsyncSend), pipeStream);

        //there is more than 1 server present
        for (int i = 1; i < _serverCount; i++)
            {
                //create another client copy and use it
                NamedPipeClientStream pipeStream2 = new NamedPipeClientStream
                (".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous);

                pipeStream2.Connect(TimeOut);

                byte[] buffer2 = Encoding.UTF8.GetBytes(SendStr);
                pipeStream2.BeginWrite(buffer2, 0, buffer2.Length, AsyncSend, pipeStream2);
            }
    }
    catch (TimeoutException oEX)
    {    ...        }
}

Note that this code doensn't handle situation when NumberOfServerInstances changes while cycle is running (sudden server instance closing, etc.)

BTW Don't have any idea why MSDN suggests to use

 // Kill original sever and create new wait server
 pipeServer.Close();
 pipeServer = null;
 pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 
    -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

 // Recursively wait for the connection again and again....
 pipeServer.BeginWaitForConnection(
   new AsyncCallback(WaitForConnectionCallBack), pipeServer);

Instead I've tested simply disconnecting current client

pipeServer.Disconnect();

// Recursively wait for the connection again and again....
pipeServer.BeginWaitForConnection(
   new AsyncCallback(WaitForConnectionCallBack), pipeServer);

and it worked for me the same way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!