在C#中打开和关闭线程

Fan*_*icD 1 c# multithreading

这是事情,我已经开始使用C#,我想做这样的事情:

我有一个带有一个按钮和图片框的Windows窗体应用程序.

单击按钮应该导致实际状态的属性"正在运行"为真/假.这样就完成了.

此外,它应该导致打开将在程序运行时不断完成工作的脚本.这个"作业"将在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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我可以完全点击按钮两次,看起来一切都很好......但是当我第三次点击它时,会弹出错误:

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

An unhandled exception of type 'System.Threading.ThreadStateException' occurred in mscorlib.dll

Additional information: Thread is running or terminated; it cannot restart.
Run Code Online (Sandbox Code Playgroud)

提前感谢您提供给我的任何帮助.

Ali*_*eza 5

唯一的例外是自我解释

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

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

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