因此,我终于找到了一个解决方案(不确定它是最优的,但它是有效的)。它基于使用
NamedPipeClientStream.NumberOfServer实例
.
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)
{ ... }
}
请注意,当NumberOfServerInstance在循环运行时发生变化时(突然关闭服务器实例等),此代码不会处理这种情况
顺便提一下
不知道MSDN为什么建议使用
// 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);
相反,我只测试了断开当前客户端的连接
pipeServer.Disconnect();
// Recursively wait for the connection again and again....
pipeServer.BeginWaitForConnection(
new AsyncCallback(WaitForConnectionCallBack), pipeServer);
对我来说也是如此。