Is there a way to wake a sleeping thread?

Viewed 27558

Is there a way to wake a sleeping thread in C#? So, have it sleep for either a long time and wake it when you want work processed?

7 Answers

Expanding Wim's answer you can also specify a timeout for the WaitHandle.WaitOne() call. So you can use instead of Thread.Sleep(). CancellationToken struct provides you with one so you can signal your tasks like this:

string SleepAndWakeUp(string value,CancellationToken ct)
{
    ct.WaitHandle.WaitOne(60000);
    return value;
}

void Parent()
{
     CancellationTokenSource cts = new CancellationTokenSource();
     Task.Run(() => SleepAndWakeUp("Hello World!", cts.Token), cts.Token);
     //Do some other work here
     cts.Cancel(); //Wake up the asynch task
}

Based on Ilia's suggestion:

t1 = new Thread(() =>
    {
     while (keepRunning) {
         try {
             DoWork();
             Thread.Sleep(all_night_long);
             }
         catch (ThreadInterruptedException) { }
         }
    });
t1.Start();

and...

public void WakeUp()
{
   t1.Interrupt();
}

public void StopRunningImmediately()
{
   keepRunning = false;
   WakeUp(); //immediately
}

This solution is crude, as there may be other reasons why the ThreadInterruptedException is thrown.

Related