杀死 .NET 线程 [英] Killing a .NET thread
问题描述
我创建了一个运行特定方法的线程.但有时我想杀死线程,即使它仍在工作.我怎样才能做到这一点?我尝试了 Thread.Abort() 但它显示了一个消息框,上面写着线程中止".我该怎么办?
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()
!
Thread.Abort
是危险的.相反,您应该与线程合作,以便它可以和平关闭.线程需要被设计成可以告诉它自我终止,例如通过设置一个布尔值 keepGoing
标志,当你希望线程停止时,将其设置为 false.然后该线程将具有类似
Do not call 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
while (keepGoing)
{
/* Do work. */
}
如果线程可能在 Sleep
或 Wait
中阻塞,那么您可以通过调用 Thread.Interrupt()
.然后线程应该准备好处理 ThreadInterruptedException
:
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
:
try
{
while (keepGoing)
{
/* Do work. */
}
}
catch (ThreadInterruptedException exception)
{
/* Clean up. */
}
这篇关于杀死 .NET 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!