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

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

问题描述

我创建了一个客户端 - 服务器应用程序,在服务器上,我想有机会停止服务器,然后再次启动它。问题是我不能停止侦听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.

如何关闭C#中的线程?

How can I close a Thread in C#?

谢谢。

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


推荐答案

一般,你应该停止线程,通过指示你希望他们停止,让他们做。建议您不要使用 Thread.Abort ,除非您正在关闭整个应用程序的紧急情况。 (调用 Thread.Abort 在当前正在执行的线程更安全,但仍然一般icky。这是ASP.NET做什么时,当你重定向,顺便说一句。)

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.

现在,应用在你的特定情况将取决于你如何监听TCP连接。如果您可以发布该线程使用的代码,我们可以适当调整。

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天全站免登陆