我有此代碼後...停止一個的TcpListener調用BeginAcceptTcpClient
internal static void Start()
{
TcpListener listenerSocket = new TcpListener(IPAddress.Any, 32599);
listenerSocket.Start();
listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
}
然後我的回調函數看起來像這樣...
private static void AcceptClient(IAsyncResult asyncResult)
{
MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
ThreadPool.QueueUserWorkItem((object state) => handler.Process());
listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
}
現在,我打電話BeginAcceptTcpClient,然後一段時間後來我想停止服務器。爲此,我一直在調用TcpListener.Stop()或TcpListener.Server.Close()。這兩個都執行我的AcceptClient函數。當我調用EndAcceptTcpClient時,這會引發異常。什麼是最好的實踐方式呢?一旦我呼叫停止,我可以放一個標誌來阻止AcceptClient的執行,但是我想知道我是否錯過了一些東西。
更新1
目前我已經通過改變代碼看起來像這樣修補它。
private static void AcceptClient(IAsyncResult asyncResult)
{
if (!shutdown)
{
MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
ThreadPool.QueueUserWorkItem((object state) => handler.Process());
listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
}
}
private static bool shutdown = false;
internal static void Stop()
{
shutdown = true;
listenerSocket.Stop();
}
更新2
我改成了impliment從斯賓塞Ruport答案。
private static void AcceptClient(IAsyncResult asyncResult)
{
if (listenerSocket.Server.IsBound)
{
MessageHandler handler = new MessageHandler(listenerSocket.EndAcceptTcpClient(asyncResult));
ThreadPool.QueueUserWorkItem((object state) => handler.Process());
listenerSocket.BeginAcceptTcpClient(new AsyncCallback(AcceptClient), null);
}
}
您不必排隊另一個線程來完成處理工作;您可以調用EndAcceptTcpClient來告訴偵聽器處理它,然後在它之後調用BeginAcceptTcpClient來安排另一個處理。使用當前線程處理您剛收到的請求。 – 2010-11-26 15:42:46