如何在 C# 中停止线程?

How can I stop a thread in C#?(如何在 C# 中停止线程?)

本文介绍了如何在 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 更安全,但通常还是很麻烦.顺便说一句,这就是 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# 中停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 C# 中停止线程?