0

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

Username Not Exist
  • 491
  • 2
  • 5
  • 13

2 Answers2

0

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#)

Community
  • 1
  • 1
user8128167
  • 6,929
  • 6
  • 66
  • 79
0

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();
    }
fliedonion
  • 912
  • 8
  • 13