简体   繁体   中英

thread start stop c# WinForm

Background: In C# WinForm, I use several Threads like this

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

And I want to set a timer to Stop/Kill the Thread1 every hour, and restart a new Thread1 like this:

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

So How to kill the thread1 and restart a new one without Restart my Winform?

Thank you kindly for your reply. I much appreciated it

Here is a sample.

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

    }

I don't recommend Thread.Abort method.
When possible, design the thread what can stop safety. And use Join method.

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

You can do so by having a while loop in DoSomething that continues based on a volatile bool. Please see Groo's answer here:

Restarting a thread in .NET (using C#)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM