我有一个包含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