线程启动停止c#WinForm

时间:2014-06-19 16:08:56

标签: c# multithreading winforms

背景: 在C#WinForm中,我使用了几个这样的线程

private Thread Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();

我想设置一个计时器每小时停止/杀死Thread1,然后重启一个新的Thread1:

Abort/Kill Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();

那么如何在不重启我的Winform的情况下杀死thread1并重启一个新的?

谢谢你的回复。我非常感激

2 个答案:

答案 0 :(得分:1)

以下是一个示例。

    private void button1_Click(object sender, EventArgs e) {

        var i = 0;
        Action DoSomething = () => {
            while (true) {
                (++i).ToString();
                Thread.Sleep(100);
            }
        };

        Thread Thread1;
        Thread1 = new Thread(new ThreadStart(DoSomething));
        Thread1.Start();

        Thread.Sleep(1000);
        Text = i.ToString();

        Thread1.Abort();
        Thread1 = new Thread(new ThreadStart(DoSomething));
        Thread1.Start();

    }

我不推荐使用Thread.Abort方法 如果可能,设计可以阻止安全的线程。并使用Join方法。

    private void button2_Click(object sender, EventArgs e) {

        // the flag, to stop the thread outside.
        var needStop = false;

        var i = 0;
        Action DoSomething = () => {
            while (!needStop) {
                (++i).ToString();
                Thread.Sleep(100);
            }
        };


        Thread Thread1;
        Thread1 = new Thread(new ThreadStart(DoSomething));
        Thread1.Start();

        Thread.Sleep(1000);
        Text = i.ToString();

        // change flag to stop.
        needStop = true;
        // wait until thread stop.
        Thread1.Join();

        // start new thread.
        Thread1 = new Thread(new ThreadStart(DoSomething));
        Thread1.Start();

        // needStop = true;
        // Thread1.Join();
    }

答案 1 :(得分:0)

你可以通过在DoSomething中使用while循环继续基于volatile bool来实现。请在这里看到Groo的答案:

Restarting a thread in .NET (using C#)