如何停止在C#中的线程? [英] How can I stop a thread in C#?

查看:1144
本文介绍了如何停止在C#中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个客户端 - 服务器应用程序,并在服务器上我想有oportunity停止服务器,然后再次启动它。问题是,我不能停止监听TCP连接线程。



如何在C#中关闭一个主题?



感谢。

 私人无效KeepServer(){
,而(this.connected)
{
的TcpClient = tls.AcceptTcpClient();
连接newConnection =新的连接(TcpClient的);
}
}


解决方案

在一般情况下,你应该表明你希望他们停止,并让他们做停止线程。它建议您的的使用 Thread.Abort的除非你在哪里关闭整个应用程序的紧急情况。 (呼叫 Thread.Abort的在当前执行的线程安全,但仍普遍恶心。这就是当你重定向ASP.NET做什么的,顺便说一句。)



我有关于停止线程页面优雅的。您不必使用该确切的代码,当然 - 但设置标志和测试周期性的主要点的格局



现在,如何得到这在特定情况下应用将取决于你如何监听TCP连接。如果你能发布由该线程使用的代码,我们也许能够适当地适应它。


I've created a Client-Server application, and on the Server I want to have the oportunity to stop the server and then start it again. The problem is that I can't stop the Thread that listen for Tcp Connections.

How can I close a Thread in C#?

Thanks.

private void KeepServer(){
    while (this.connected)
    {
         tcpClient = tls.AcceptTcpClient();
         Connection newConnection = new Connection(tcpClient);
    }
}

解决方案

In general, you should "stop" threads by indicating that you want them to stop, and letting them do it. It's recommended that you don't use Thread.Abort except for emergency situations where you're shutting down the whole application. (Calling Thread.Abort on the currently executing thread is safer, but still generally icky. That's what ASP.NET does when you redirect, by the way.)

I have a page about stopping threads gracefully. You don't have to use that exact code, of course - but the pattern of setting a flag and testing it periodically is the main point.

Now, how that gets applied in your particular situation will depend on how you're listening for TCP connections. If you could post the code used by that thread, we may be able to adapt it appropriately.

这篇关于如何停止在C#中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆