C# 杀死 .NET 线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1051838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Killing a .NET thread
提问by Jorge Branco
I have created a thread running a certain method. But sometimes I would like to kill the thread even if it is still working. How can I do this? I tried Thread.Abort() but it shows up a messagebox saying "Thread aborted". What should I do?
我创建了一个运行某种方法的线程。但有时我想杀死线程,即使它仍在工作。我怎样才能做到这一点?我尝试了 Thread.Abort() 但它显示了一个消息框,上面写着“线程中止”。我该怎么办?
回答by Jon B
You should really only call Abort() as a last resort. You can use a variable to sync this thread instead:
你真的应该只调用 Abort() 作为最后的手段。您可以使用变量来同步此线程:
volatile bool shutdown = false;
void RunThread()
{
while (!shutdown)
{
...
}
}
void StopThread()
{
shutdown = true;
}
This allows your thread to cleanly finish what it was doing, leaving your app in a known good state.
这允许您的线程干净利落地完成它正在做的事情,让您的应用程序处于已知的良好状态。
回答by John Saunders
Aborting a thread is a very bad idea, since you cannot determine what the thread was doing at the time of the abort.
中止线程是一个非常糟糕的主意,因为您无法确定中止时线程正在做什么。
Instead, have a property that the thread can check, and that your external code can set. Let the thread check this boolean property when it's at a safe place to exit.
相反,拥有一个线程可以检查的属性,并且您的外部代码可以设置该属性。当线程在一个安全的地方退出时,让线程检查这个布尔属性。
回答by John Kugelman
Do not call Thread.Abort()
!
不要打电话Thread.Abort()
!
Thread.Abort
is dangerous. Instead you should cooperate with the thread so that it can be peacefully shut down. The thread needs to be designed so that it can be told to kill itself, for instance by having a boolean keepGoing
flag that you set to false when you want the thread to stop. The thread would then have something like
Thread.Abort
是危险的。相反,您应该与线程合作,以便它可以和平关闭。线程需要设计为可以告诉它自行keepGoing
终止,例如通过设置一个布尔标志,当您希望线程停止时将其设置为 false。然后线程会有类似的东西
while (keepGoing)
{
/* Do work. */
}
If the thread may block in a Sleep
or Wait
then you can break it out of those functions by calling Thread.Interrupt()
. The thread should then be prepared to handle a ThreadInterruptedException
:
如果线程可以在阻止Sleep
或Wait
那么你可以通过调用打破它的这些功能Thread.Interrupt()
。然后线程应该准备好处理一个ThreadInterruptedException
:
try
{
while (keepGoing)
{
/* Do work. */
}
}
catch (ThreadInterruptedException exception)
{
/* Clean up. */
}
回答by Mark Seemann
The most correct and thread-safe way is to use a WaitHandle to signal to the thread when it's supposed to stop. I mostly use ManualResetEvent.
最正确和线程安全的方法是在线程应该停止时使用 WaitHandle 向线程发出信号。我主要使用 ManualResetEvent。
In your thread, you can have:
在您的线程中,您可以拥有:
private void RunThread()
{
while(!this.flag.WaitOne(TimeSpan.FromMilliseconds(100)))
{
// ...
}
}
where this.flag
is an instance of ManualResetEvent. This means that you can call this.flag.Set()
from outside the thread to stop the loop.
其中this.flag
是 ManualResetEvent 的一个实例。这意味着您可以this.flag.Set()
从线程外部调用来停止循环。
The WaitOne method will only return true when the flag is set. Otherwise, it will time out after the specified timeout (100 ms in the example) and the thread will run through the loop once more.
WaitOne 方法只会在设置标志时返回 true。否则,它将在指定的超时(示例中为 100 毫秒)后超时,线程将再次运行循环。
回答by Brian Gideon
It is not a good idea to kill a thread. It is better to signal that it should stop and let it end gracefully. There are various different ways of doing this.
杀死线程不是一个好主意。最好发出信号表明它应该停止并让它优雅地结束。有多种不同的方法可以做到这一点。
- Use
Thread.Interrupt
to poke it if it is blocked. - Poll a flag variable.
- Use the
WaitHandle
class to send a signal.
- 使用
Thread.Interrupt
捅它,如果它被阻止。 - 轮询标志变量。
- 使用
WaitHandle
该类发送信号。
There is no need for me to rehash how each method can be used since I have already done so in this answer.
回答by XenKid
I agree to Jon B
我同意乔恩 B
volatile bool shutdown = false;
void RunThread()
{
try
{
while (!shutdown)
{
/* Do work. */
}
}
catch (ThreadAbortException exception)
{
/* Clean up. */
}
}
void StopThread()
{
shutdown = true;
}
回答by Jay
There are also examples of killing threads in my WebServer class...
在我的 WebServer 类中也有杀死线程的例子......
https://net7ntcip.codeplex.com/SourceControl/changeset/view/89621#1752948
https://net7ntcip.codeplex.com/SourceControl/changeset/view/89621#1752948
I would say Abort is okay just understand what the ramifications are... as long as you are indicating state before a long running task Abort will work but flags are required such as (ShouldStop or ActionBranch etc)
我会说 Abort 没问题,只要了解后果是什么……只要您在长时间运行的任务 Abort 之前指示状态即可,但需要标志,例如(ShouldStop 或 ActionBranch 等)
Check it out for examples!
看看它的例子!