c# Stop Thread with a button click

风流意气都作罢 提交于 2021-02-17 05:37:21

问题


How can I end my thread with a button click? I start my thread with a button click.

new Thread(SampleFunction).Start();

and my thread:

    void SampleFunction()
    {
        int i = 0;
        while (true)
        {
            string Seconds = DateTime.Now.ToString("ss");
            if (Seconds == "00")
            {
                int i2 = i++;
                string myString = i2.ToString();
                AppendTextBox(myString);
                Thread.Sleep(2000);
            }                
        }
    }

    public void AppendTextBox(string value)
    {
        if (InvokeRequired)
        {
            this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
            return;
        }
        textBox4.Text += value;
    }

How do i cancel it? the following doesn't work:

private void button8_Click(object sender, EventArgs e)
    {
     SampleFunction.Abort();
    }

回答1:


SampleFunction is a method, not a Thread object, so you can't call Abort() like that.

You need to keep a reference to the Thread:

var thread = new Thread(SampleFunction);
thread.Start();

Then you can call Abort() when you want to kill it:

thread.Abort();

But keep in mind that it does kill it. The effect of Abort() is that it throws a ThreadAbortException in the thread. So it can stop at any moment and leave things in an unexpected state, so it may not be the best approach depending on what you're doing in the thread.

Here are a couple articles that discuss this and possibly better ways to stop a thread:

  • Destroying threads
  • Canceling threads cooperatively


来源:https://stackoverflow.com/questions/53462913/c-sharp-stop-thread-with-a-button-click

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