且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在我的C#应用​​程序中杀死线程?

更新时间:2021-12-04 22:42:57

请参阅此文章,以了解为什么您永远不要尝试调用Thread.Abort:

See this article for why you should never try to call Thread.Abort:

http://www.interact-sw.co. uk/iangblog/2004/11/12/cancellation

问题是您破坏了该线程中的异常安全性.这是因为Thread.Abort会在任意点在该线程内引发异常,这可能恰好在加载资源之后但在线程进入尝试支持该资源的干净卸载的try/catch之前.

The problem is that you break your exception safety within that thread. This is because Thread.Abort will throw an exception within that thread at some arbitrary point, which might be right after a resource is loaded, but before the thread enters a try/catch that would support clean unloading of that resource.

相反,您应该在该线程中运行的代码中内置协作取消功能.然后设置某种取消请求"状态,并让线程杀死自己.例如:

Instead you should build co-operative cancellation into the code you run in that thread. Then set some sort of "cancellation requested" state, and let the thread kill itself. E.g.:

foreach(var value in aBunchOfData)
{
    if(isCancelled)
    {
        break;
    }

    // Continue processing here...
}

在这种情况下,您将公开isCancelled,并将您的父线程将其设置为true.

In this case you'd expose isCancelled, and have your parent thread set it to true.

如果您使用BackgroundWorker来实现您的后台线程.

This pattern is made clear if you use a BackgroundWorker to implement your background thread.