正确完成服务器线程 [英] Correct finishing of server's thread
本文介绍了正确完成服务器线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有Windows窗体.在构造函数中服务器线程启动
I have windows form. In the constructor server thread starts
thServer = new Thread(ServerThread);
thServer.Start();
在服务器线程中有TCP侦听器循环:
In the server thread there is TCP listener loop:
while (true) {
TcpClient client = server.AcceptTcpClient();
...
}
当我关闭主窗体时,该线程继续等待TCPClient的请求.如何停止此例程? 谢谢你.
When I close main form, this thread continues to wait TCPClient's requests. How can I stop this routine? Thank you.
推荐答案
public partial class Form1 : Form
{
Thread theServer = null;
public Form1()
{
InitializeComponent();
this.FormClosed += new FormClosedEventHandler( Form1_FormClosed );
theServer = new Thread( ServerThread );
theServer.IsBackground = true;
theServer.Start();
}
void ServerThread()
{
//TODO
}
private void Form1_FormClosed( object sender, FormClosedEventArgs e )
{
theServer.Interrupt();
theServer.Join( TimeSpan.FromSeconds( 2 ) );
}
}
这篇关于正确完成服务器线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文