我有一个用C#编写的命名管道服务器。实现的要点是:
void BeginWaitForNextConnection()
{
var pipe = new NamedPipeServerStream(
PipeName,
PipeDirection.InOut,
NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous,
0, // default in buffer size
0, // default out buffer size
CreateAllAccessPipeSecurity());
pipe.BeginWaitForConnection(ClientRequestHandler, pipe);
}
void ClientRequestHandler(IAsyncResult ar)
{
// Clean up the async call state.
NamedPipeServerStream pipe = (NamedPipeServerStream)ar.AsyncState;
pipe.EndWaitForConnection(ar);
// If we've been asked to shut down, go away.
if (_stopping)
{
pipe.Close();
return;
}
// Set up for the next caller.
BeginWaitForNextConnection();
// Handle this client's I/O. This code wraps the pipe stream in BinaryReader and BinaryWriter objects and handles communication with the client.
HandlePipeClient(pipe);
}
这非常正常-直到多个实例尝试快速连续连接为止。我的客户代码指定了10秒钟的超时时间,因此我希望即使10个实例在同一秒内尝试连接,它们也应全部成功,因为此代码在{{{ 1}}回调到ClientRequestHandler
中-但这确实是我所看到的。对于偶尔的一次性连接,此代码非常可靠,但是如果我遇到了频繁的请求,则似乎在回调与下一个BeginWaitForNextConnection
之间到达连接请求时,该连接不会排队起来马上被捡起来-简直就是迷路。
这是预期的吗?什么是习惯上正确的解决方案?我是否只需要整理一个一堆完整的线程一次就等待连接?