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?
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
}