Search code examples
c#multithreadingtimer

Reliably stop System.Threading.Timer?


Well I've searched a lot for a solution to this. I'm looking for a clean and simple way to prevent the callback method of a System.Threading.Timer from being invoked after I've stopped it.

I can't seem to find any, and this has led me, on occassion, to resort to the dreaded thread-thread.sleep-thread.abort combo.

Can it be done using lock?


Solution

  • like Conrad Frix suggested you should use the System.Timers.Timer class instead, like:

    private System.Timers.Timer _timer = new System.Timers.Timer();
    private volatile bool _requestStop = false;
    
    public constructor()
    {
        _timer.Interval = 100;
        _timer.Elapsed += OnTimerElapsed;
        _timer.AutoReset = false;
        _timer.Start();
    }
    
    private void OnTimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // do work....
        if (!_requestStop)
        {
            _timer.Start();//restart the timer
        }
    }
    
    private void Stop()
    {
        _requestStop = true;
        _timer.Stop();
    }
    
    private void Start()
    {
        _requestStop = false;
        _timer.Start();
    }