当我想为每个传入请求打开一个新线程时。这是一个好方法吗?每个接受的请求都会有一个新线程吗?在这段代码末尾调用的 BeginReceive 方法也可以异步工作。
public void Listen(IPEndPoint EndPoint)
{
try
{
ListeningSocket.Bind(EndPoint);
ListeningSocket.Listen(BACKLOG);
BeginAccept();
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\nfrom Source: " + e.Source + "\nand Stack Trace: " + e.StackTrace);
}
}
public void BeginAccept()
{
try
{
ListeningSocket.BeginAccept(new AsyncCallback(Accept_Callback), new ServerSocket());
}
catch (SocketException e)
{
Console.WriteLine("Listening Socket Error:" + e.ErrorCode);
}
catch (ObjectDisposedException e)
{
Console.WriteLine("The Listening Socket has been closed");
}
}
private void Accept_Callback(IAsyncResult asyncResult)
{
BeginAccept();
try
{
if (asyncResult.AsyncState != null)
{
ServerSocket serverSocket = asyncResult.AsyncState as ServerSocket;
if ((serverSocket.CommunicationSocket = ListeningSocket.EndAccept(asyncResult)) != null)
{
BeginReceive(serverSocket);
}
}
}
catch (SocketException e)
{
Console.WriteLine("Listening Socket Error:" + e.ErrorCode);
}
catch (ObjectDisposedException e)
{
Console.WriteLine("The Listening Socket has been closed");
}
}