打开&c#中的off线程

本文关键字:off 线程 中的 打开 | 更新日期: 2023-09-27 18:12:45

事情是这样的,我从c#开始,我想做这样的事情:

我有一个Windows窗体应用程序与一个按钮和图片框。

点击一个按钮应该导致将属性"Running"变为true/false,根据实际状态。

同样,它应该导致打开脚本,该脚本将在程序运行时不断地执行任务。这个"作业"将在Run()方法中描述。我希望这个方法只在Running == true时执行,当它变为false时,该方法应该结束。所以我决定把它放到线程中,在我在Running = true和Running = false之间切换的方法中,我尝试启动线程并中止它。

我为什么要这样做?因为我希望能够通过我在开始时提到的按钮来打开和关闭程序。

这是我想到的:

        Thread thProgram;

    public Form1()
    {
        InitializeComponent();
        thProgram = new Thread(new ThreadStart(this.Run));
    }
    private bool Running = false;

    public void Run()
    {
        int i = 0;
        while(this.Running)
        {
            i++;
        }
        MessageBox.Show("Terminated");
    }
     // handling bot activation button (changing color of a pictureBox1), switching this.Running property
    private void button1_Click(object sender, EventArgs e)
    {
        if(this.Running)
        {
            thProgram.Abort();
            pictureBox1.BackColor = Color.Red;
            this.Running = false;
        }
        else
        {
            thProgram.Start();
            pictureBox1.BackColor = Color.Lime;
            this.Running = true;
        }
    }

我正好按了两次按钮,看起来一切都很正常…但是当我第三次点击它时,错误弹出:

(它突出显示行"thProgram.Start();"

An unhandled exception of type 'System.Threading.ThreadStateException' occurred in mscorlib.dll
Additional information: Thread is running or terminated; it cannot restart.

提前感谢你能提供给我的任何帮助。

打开&c#中的off线程

self - explained

当您第一次按下按钮时,线程启动并进入主循环。第二个按钮按下中止线程(这总是一个坏主意)。您使用的标志就足够了),线程终止。

按下第三个按钮?Thread.Start()的MSDN文档:

Once the thread terminates, it cannot be restarted with another call to Start.

要冻结线程而不终止它,我建议使用AutoResetEvent:

public Form1()
{
    InitializeComponent();
    thProgram = new Thread(new ThreadStart(this.Run));
}
private bool Running = false;
private AutoResetEvent ThreadHandle = new AutoResetEvent(false);

public void Run()
{
    int i = 0;
    while(true)
    {
        ThreadHandle.WaitOne();
        i++;
    }
    MessageBox.Show("Terminated");
}
 // handling bot activation button (changing color of a pictureBox1), switching this.Running property
private void button1_Click(object sender, EventArgs e)
{
    if(this.Running)
    {
        thProgram.Abort();
        pictureBox1.BackColor = Color.Red;
        this.ThreadHandle.Reset();
        this.Running = false;
    }
    else
    {
        thProgram.Start();
        pictureBox1.BackColor = Color.Lime;
        this.ThreadHandle.Set();
        this.Running = true;
    }
}