Reliably stop System.Threading.Timer? Reliably stop System.Threading.Timer? multithreading multithreading

Reliably stop System.Threading.Timer?


An easier solution might to be to set the Timer never to resume; the method Timer.Change can take values for dueTime and period that instruct the timer never to restart:

this.Timer.Change(Timeout.Infinite, Timeout.Infinite);

Whilst changing to use System.Timers.Timer might be a "better" solution, there are always going to be times when that's not practical; just using Timeout.Infinite should suffice.


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();}


The MSDN Docs suggest that you use the Dispose(WaitHandle) method to stop the timer + be informed when callbacks will no longer be invoked.