如何在 C# 中立即杀死一个线程? [英] How to kill a thread instantly in C#?

查看:68
本文介绍了如何在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆