Windows Form Application, Thread won't stop

末鹿安然 提交于 2019-12-19 04:59:14

问题


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.

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    
            }
        }
      }

.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.


回答1:


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.

Simple sample:

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    
    }
}


来源:https://stackoverflow.com/questions/12894503/windows-form-application-thread-wont-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!