如何在C#中立即杀死线程? [英] How to kill a thread instantly in C#?
问题描述
我正在使用thread.Abort
方法杀死线程,但是它不起作用.还有其他终止线程的方法吗?
I am using the thread.Abort
method to kill the thread, but it not working. Is there any other way of terminating the thread?
private void button1_Click(object sender, EventArgs e)
{
if (Receiver.IsAlive == true)
{
MessageBox.Show("Alive");
Receiver.Abort();
}
else
{
MessageBox.Show("Dead");
Receiver.Start();
}
}
我正在使用它,但是每次获得Alive
状态时,Receiver
是我的全局线程.
I am using this but every time I get the Alive
status, Receiver
is my global thread.
推荐答案
很难杀死一个线程的原因是因为语言设计者希望避免以下问题:您的线程需要一个锁,然后才将其杀死它可以释放它.现在,任何需要该锁的人都会被卡住.
The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.
您要做的是使用一些全局变量告诉线程停止.您必须手动在线程代码中检查该全局变量,如果看到它表明您应该停止,则返回该变量.
What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.
这篇关于如何在C#中立即杀死线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!