Search code examples
c#timer

How to prevent executing function after Timer Stop


on https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.stop?view=netcore-3.1, we can read that function that Timer executing that can perform after Timer Stop because its possible that Stop method would run on another thread.

I don't understand the workaround presented in this docs, could someone help me by explain how to prevent the timer from executing after the Stop function?


Solution

  • a fairly simple way would be to take a lock, preventing the object from being disposed while the event handler is running, and a flag to ensure the tick-handler does not run after the object is disposed:

    private bool disposed;
    private object disposeLock = new object();
    
    private void MyTimerTickHandler(){
        lock(disposeLock){
             if(disposed) return;
             ....
        }
    }
    
    private void Dispose(){
        lock(disposeLock){
            disposed = true;
            ...
        }
    }
    
    

    This will ensure that the content of the tick handler never runs after the object is disposed. But it also means the dispose method might block, and it might cause deadlocks unless you are careful. It might be possible to avoid the lock, but that would depend on exactly what the tick handler is doing.