c# - 终止 .NET 线程

标签 c# multithreading abort

我创建了一个运行特定方法的线程。但有时我想杀死线程,即使它还在工作。我怎样才能做到这一点?我尝试了 Thread.Abort() 但它显示了一个消息框,上面写着“Thread aborted”。我应该怎么办?

最佳答案

Do not call Thread.Abort()!

Thread.Abort 很危险。相反,您应该与线程合作,以便它可以和平关闭。线程需要设计成可以告诉它杀死自己,例如通过设置一个 bool 值 keepGoing 标志,当您希望线程停止时将其设置为 false。然后线程会有类似的东西

while (keepGoing)
{
    /* Do work. */
}

如果线程可能在SleepWait 中阻塞,那么您可以通过调用Thread.Interrupt() 将其从这些函数中分离出来。 .然后线程应该准备好处理 ThreadInterruptedException:

try
{
    while (keepGoing)
    {
        /* Do work. */
    }
}
catch (ThreadInterruptedException exception)
{
    /* Clean up. */
}

关于c# - 终止 .NET 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1051838/

相关文章:

c# - 如何在 "Visibility"类别而不是 "Other"下声明 DependencyProperty ?

c# - Azure函数: Could not load file or assembly Newtonsoft. Json

java - NullPointerException 从构造函数启动时

python 导入在 mercurial_keyring.py 文件中的行为似乎有所不同

python - Flask 中间件中止 401 导致 500

c# - 线程被中止错误

c# - 在 ASP.Net 的 gridview 中获取选中的复选框

c# - C# 中解析此日期格式 "Mon Oct 07 00:00:00 EDT 2013"的正确方法是什么?

multithreading - 使用 tkinter + pyhook 时卡住。两个事件循环和多线程

java - Java为HashSet中的ConcurrentModificationException提供的类是什么?