Is there a way to Interupt a sleeping thread? If I have code similar to this.
while(true){
if(DateTime.Now.Subtract(_lastExecuteTime).TotalHours > 1)
Instead of using Thread.Sleep
, you can use Monitor.Wait
with a timeout - and then you can use Monitor.Pulse
from a different thread to wake it up.
Don't forget you'll need to lock on the monitor before calling either Wait
or Pulse
:
// In the background thread
lock (monitor)
{
// If we've already been told to quit, we don't want to sleep!
if (somethingIndicatingQuit)
{
break;
}
Monitor.Wait(monitor, TimeSpan.FromSeconds(10));
if (somethingIndicatingQuit)
{
break;
}
}
// To wake it up...
lock (monitor)
{
somethingIndicatingQuit = true;
Monitor.Pulse(monitor);
}