有一个TcpListener类的服务器。它使用BeginAcceptTcpClient(AsyncCallback, Object)方法接受传入连接。
这段代码是在MSDN示例中编写的。
public static ManualResetEvent tcpClientConnected =
new ManualResetEvent(false);
public static void DoBeginAcceptTcpClient(TcpListener
listener)
{
while(true)
{
tcpClientConnected.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAcceptTcpClient(
new AsyncCallback(DoAcceptTcpClientCallback),
listener);
tcpClientConnected.WaitOne();
}
}
public static void DoAcceptTcpClientCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener) ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
Console.WriteLine("Client connected completed");
tcpClientConnected.Set();
while(true)
{
//Receiving messages from the client
}
}
问题在于DoAcceptTcpClientCallback(IAsyncResult ar)方法有时候会在当前线程(main)中开始执行,而不是在新线程中执行,并阻塞了它(main)。因此,接下来的连接无法被接受。 请帮忙理解为什么不为此方法创建一个新的线程。
//从客户端接收消息
由于某种原因正在切换回使用同步API调用。不要这样做。一旦你进入异步(以某种不涉及创建线程的方式),你就不知道将在哪个线程上运行 - 因此你应该只运行足以调度下一个异步方法并返回所需的时间。 - Damien_The_Unbeliever