How to let Timer skip tick if the previous thread is still busy

后端 未结 8 1674
攒了一身酷
攒了一身酷 2020-12-01 11:28

I created a windows service, that is supposed to check a certain table in the db for new rows every 60 seconds. For every new row that was added, I need to do some heavy pro

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 11:46

    You might try disabling the timer during processing, something like

    // Just in case someone wants to inherit your class and lock it as well ...
    private static object _padlock = new object();
    try
    {
      serviceTimer.Stop(); 
    
      lock (_padlock)
        { 
            // do some heavy processing... 
        } 
    }
    finally
    {
      serviceTimer.Start(); 
    }
    

    Edit : OP didn't specify whether the reentrancy was caused only by the timer or whether the service was multi threaded. Have assumed the later, but if the former then locking should be unnecessary if the timer is stopped (AutoReset or manually)

提交回复
热议问题