c#单击按钮停止线程 [英] c# Stop Thread with a button click

查看:173
本文介绍了c#单击按钮停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过单击按钮结束我的线程?我通过单击按钮开始我的线程.

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

new Thread(SampleFunction).Start();

和我的主题:

    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();
    }

推荐答案

SampleFunction 是方法,不是 Thread 对象,所以不能调用 Abort() 喜欢

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

您需要保留对 Thread 的引用:

You need to keep a reference to the Thread:

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

然后你可以在你想杀死它的时候调用Abort():

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

thread.Abort();

但请记住,它确实杀死它.Abort() 的作用是在线程中抛出一个ThreadAbortException.因此它可以随时停止并使事情处于意外状态,因此根据您在线程中执行的操作,它可能不是最佳方法.

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:

这篇关于c#单击按钮停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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