Stopping a reliable System.Timers.Timer is really a big effort. The most serious problem is that the thread threads that it uses to trigger the Elapsed event can back up due to the thread scheduler algorithm. Having multiple backup calls is not unusual, and hundreds of them are technically possible.
You will need two synchronizations, one of which ensures that you stop the timer only when the Elapsed handler is not running, the other to ensure that these backup TP threads do no harm. Like this:
System.Timers.Timer timer = new System.Timers.Timer(); object locker = new object(); ManualResetEvent timerDead = new ManualResetEvent(false); private void Timer_Elapsed(object sender, ElapsedEventArgs e) { lock (locker) { if (timerDead.WaitOne(0)) return;
Consider the AutoReset property set to false. This fragile other way, the Elapsed event is called from an internal .NET method that catches the Exception. Very unpleasant, your timer code stops working without any diagnostics at all. I don't know the story, but there must have been another team in MSFT that annoyed and puffed out this mess and wrote System.Threading.Timer. Highly recommended.
Hans passant
source share