Windows窗体应用程序,线程不会停止 [英] Windows Form Application, Thread won't stop

查看:99
本文介绍了Windows窗体应用程序,线程不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows Form应用程序进行线程演示.当我单击button1时,它将启动线程并递归执行工作.

I am using Windows Form application for my thread demo. When I click on button1 ,It will start the thread and recursively doing a work.

这里,表格不会像我预期的那样挂起.当我单击Button2时,我想停止当前正在运行的线程.但是,这行不通.

Here the Form will not hang as I expected. I want to Stop the currently running thread when I click on Button2. However this won't work.

        private void button1_Click(object sender, EventArgs e)
        {
            t = new Thread(doWork);          // Kick off a new thread
            t.Start();               
        }

        private  void button2_Click(object sender, EventArgs e)
        {                
            t.Abort();
        }    

        static void doWork()
        {    
            while (true)
            {
              //My work    
            }
        }
      }

.Im调试时,button2_Click方法不会命中指针.我认为是因为Thread很忙.

.When Im debugging, the button2_Click method won't hit the pointer. I think because Thread is keep busy.

如果我在某个地方出错,请纠正我.

Please correct me if I going wrong somewhere.

推荐答案

您无法杀死这样的线程.原因是要避免在线程中添加锁然后在释放锁之前将其杀死的情况.

You can't kill thread like this. The reason is to avoid situations where you add lock in thread and then kill it before lock is released.

您可以创建全局变量并使用它来控制线程.

You can create global variable and control your thread using it.

简单示例:

private volatile bool m_StopThread;

private void button1_Click(object sender, EventArgs e)
{
    t = new Thread(doWork);          // Kick off a new thread
    t.Start();               
}

private  void button2_Click(object sender, EventArgs e)
{                
    m_StopThread = true;
}    

static void doWork()
{    
    while (!m_StopThread)
    {
          //My work    
    }
}

这篇关于Windows窗体应用程序,线程不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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