Interrupt a sleeping Thread

后端 未结 7 1123
暗喜
暗喜 2020-12-13 16:08

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)         


        
7条回答
  •  失恋的感觉
    2020-12-13 16:15

    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);
    }
    

提交回复
热议问题