我有一個包含form1和program.cs文件的winform應用程序。在program.cs中我初始化form1,除此之外,我有一臺服務器。我的問題是:當我關閉表單時,如何停止線程?這裏是我的Program.cs文件的一部分:停止線程
public void start()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
//MessageBox.Show("in thread");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
sThread a = new sThread(form1, listaThreads);
listaThreads.Add(a);
Thread clientThread = new Thread(new ParameterizedThreadStart(a.HandleClientComm));
clientThread.Start(client);
}
}
tcpListener.Close();不存在。我發現tcpListener.Close(); AcceptTcpClient給出以下錯誤:阻塞操作被WSACancelBlockingCall調用中斷 – Alex 2010-11-09 09:23:23
我相信'WSACancelBlockingCall'是在這裏終止阻塞調用的正確方法。您應該將該異常視爲關閉該線程的觸發器。我首先要用'BeginAcceptTcpClient'回答,但這是您在不使用異步版本的調用時終止線程的方式。 – 2010-11-09 09:30:12
我解決了它:使用此代碼:嘗試 { client = this.tcpListener。AcceptTcpClient(); } catch { break; } – Alex 2010-11-09 10:35:10