Reputation: 873
I have three threads: the main thread and two timers. The first timer activates the second one after a period of time and then disables itself.
I use "Thread.Sleep(int)" in order to delay the activation of the second timer. But the whole program pauses when the "Sleep" function is working.
How can I pause a thread without pausing the whole program?
Upvotes: 1
Views: 13087
Reputation: 144
This program will start the first timer after 3 seconds. The first timer will stop after starting the second timer. The second timer will raise events every second after that:
class Program
{
static void Main(string[] args)
{
Timer t1 = new Timer();
t1.Elapsed += new ElapsedEventHandler(t1_Elapsed);
t1.AutoReset = false;
t1.Interval = 5000;
t1.Start();
while (true)
{ }
}
static void t1_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("t1 timer elapsed");
Timer t2 = new Timer();
t2.Elapsed += new ElapsedEventHandler(t2_Elapsed);
t2.AutoReset = true;
t2.Interval = 1000;
t2.Start();
}
static void t2_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("t2 timer elapsed");
}
}
Upvotes: 0
Reputation: 24769
Timers don't execute your code in new threads. After their interval they raise an event in the Windows Message Queue that the main thread then executes, hence why Thread.Sleep(int)
is pausing everything.
To fix this, you'll need to actually start your own threads. It's an easy process:
Thread t = new Thread(new ThreadStart(() => {
// Do Something without parameters
}));
t.Start();
or
Thread t = new Thread(new ParameterizedThreadStart((obj) => {
// Do Something with parameters
}));
Object obj = ...;
t.Start(obj);
There are other parameters you may want to set on a thread before you start it that will affect the rest of your application such as IsBackground
Upvotes: 3
Reputation: 3768
You can use the continuation style programming of the Task Parallel library.
Upvotes: 0