简体   繁体   中英

C# Is there a way to "restart" a thread when a timer is triggered?

I want to make a program that contains 2 threads that are repeatedly invoked every time the timer is triggered.

I know you can't technically restart a thread, but I was wondering is there any work around to fix the problem?

using System; 
using System.Threading; 

public class Program { 

    // static method one 
    static void method1() 
    { 
        // some code here
    } 

    // static method two 
    static void method2() 
    { 
        // some code here
    } 

    // Main Method 
    public void Main() 
    { 
        // Creating and initializing timer
        System.Timers.Timer MyTimer = new System.Timers.Timer();
        MyTimer.Interval = 4000;
        MyTimer.Tick += new EventHandler(timer1_Tick);
        MyTimer.Start();
        autoResetEvent = new AutoResetEvent(false);

        // Creating and initializing threads 
        Thread thr1 = new Thread(method1); 
        Thread thr2 = new Thread(method2);

        thr1.Start(); 
        thr2.Start(); 
    } 

    private void timer1_Tick(object sender, EventArgs e)
    {
        // code below is wrong. I want to repeat/restart the threads
        thr1.Start(); 
        thr2.Start();
    }
} 

The answer is no...

Additionally, i would seriously consider using tasks instead of the Thread class.

However, if you really must use Thread , you can create it again then Start it

Option 2 (and probably less prone to problems), is put a loop in your thread and use something like an AutoResetEvent to fire that it should continue in the loop

This is a bit of a "generic" answer, but the only solution I can think of is in your timer1_Tick function, destroy/stop the old threads and make new ones, which would look something like this:

// make sure the threads are stopped.
thr1.Stop();
thr2.Stop();

// make and start new threads.
thr1 = new Thread(method1); 
thr2 = new Thread(method2);
thr1.Start();
thr2.Start();

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