我有一个用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秒来循环10次“ClientRequestHandler”回调并进入“BeginWaitForNextConnection”——但这正是我看到的情况。对于偶尔的单次连接,这段代码非常可靠,但如果频繁请求,似乎如果在回调和下一个“BeginWaitForConnection”之间到达连接请求,那么该连接不会排队并立即被接收,而是会丢失。
这是否是预期的?什么是惯用的正确解决方案?我只需要启动许多线程同时等待连接吗?
Process.Create
,那么似乎不可能触发这个问题,即使有100个客户端尽可能快地启动。但是,如果我在TCC中输入for /L %i in (1,1,50) do start Client.exe
,那么无法连接到服务器的客户端数量会显著但不可预测地增加。 - undefined