Interrupt a sleeping Thread

后端 未结 7 1122
暗喜
暗喜 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:31

    If you want to DoWork() every hour, why not calculate the numer of ms required until the next hour is up and wait for that time? To cancel the sleep, you could either use a waitable synchro class, like the monitor as suggested by @Jon Skeet, or just set a flag in the thread that tells it to exit after the sleep instead of DoWork() and just forget about it - either the thread will kill itself when the time is up or your OS will kill it on app close, whichever comes first.

    Rgds, Martin

提交回复
热议问题