Reputation: 21
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();
}
}
Upvotes: 0
Views: 238
Reputation: 3
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();
Upvotes: -1
Reputation: 81523
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
Upvotes: 3