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?
We can wake the thread by calling either the notify() or notifyAll() methods on the monitor that is being waited on. Use notifyAll() instead of notify() when you want to wake all threads that are in the waiting state.
The answer is to create a condition object and use its wait() method with the optional timeout instead of time. sleep(). If the thread needs to be woken prior to the timeout, call the notify() method of the condition object.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException.
An AutoResetEvent
object (or another WaitHandle
implementation) can be used to sleep until a signal from another thread is received:
// launch a calculation thread
var waitHandle = new AutoResetEvent(false);
int result;
var calculationThread = new Thread(
delegate
{
// this code will run on the calculation thread
result = FactorSomeLargeNumber();
waitHandle.Set();
});
calculationThread.Start();
// now that the other thread is launched, we can do something else.
DoOtherStuff();
// we've run out of other stuff to do, so sleep until calculation thread finishes
waitHandle.WaitOne();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With