我有一个用 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 个实例尝试在同一秒内连接,它们都应该成功,因为此代码循环通过 10 次ClientRequestHandler
回调迭代不应该花费 10 秒进入BeginWaitForNextConnection
——但这确实是我所看到的。对于偶尔的一次性连接,此代码非常可靠,但如果我频繁请求它,似乎如果在回调和下一个之间到达连接请求,则BeginWaitForConnection
该连接不会排队并被拾取立即——它只是迷路了。
这是预期的吗??什么是惯用正确的解决方案?我是否只需要同时处理一大堆等待连接的线程?