Interrupt a sleeping Thread

后端 未结 7 1137
暗喜
暗喜 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 use ManualResetEvent.WaitOne.

    while (true) {
        if(DateTime.Now.Subtract(_lastExecuteTime).TotalHours > 1) {
            DoWork();
            _lastExecuteTime = DateTime.Now();
            continue; 
        }
        if (terminate.WaitOne(10000)) {
            break;
        }
    }
    

    Where terminate is a ManualResetEvent1 that you can Set to request termination of the loop.

    Update:

    I just noticed that you said you are already using ManualResetEvent to terminate the background work (I am assuming that is in DoWork). Is there any reason why you cannot use the same MRE? If that is not possible there certainly should not be an issue using a different one.

    Update 2:

    Yeah, so instead of Thread.Sleep(5000) in ExecuteWorker do _shutdownEvent.WaitOne(5000) instead. It would look like the following.

    private void ExecuteWorker() {
        while (true) {
            _pauseEvent.WaitOne(Timeout.Infinite);
    
            //This kills our process
            if (_shutdownEvent.WaitOne(0)) {
               break;
            }
    
            if (!_worker.IsReadyToExecute) {
                //sleep 5 seconds before checking again. If we go any longer we keep our service from shutting down when it needs to.
                _shutdownEvent.WaitOne(5000);
                continue;
            }
            DoWork();
        }
    }
    

    1There is also a ManualResetEventSlim class in .NET 4.0.

提交回复
热议问题