System.Timers.Timer Elapsed event executing after timer.Stop() is called

I did a pause in timer with this code. for me that works.

Private cTimer As New System.Timers.Timer
Private Sub inittimer()
    cTimer.AutoReset = True
    cTimer.Interval = 1000
    AddHandler cTimer.Elapsed, AddressOf cTimerTick
    cTimer.Enabled = True
End Sub

Private Sub cTimerTick()
    If cTimer.AutoReset = True Then
       'do your code if not paused by autoreset false
    End If
End Sub

This is well known behavior. System.Timers.Timer internally uses ThreadPool for execution. Runtime will queue the Timer in threadpool. It would have already queued before you have called Stop method. It will fire at the elapsed time.

To avoid this happening set Timer.AutoReset to false and start the timer back in the elapsed handler if you need one. Setting AutoReset false makes timer to fire only once, so in order to get timer fired on interval manually start timer again.

yourTimer.AutoReset = false;

private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
     try
     {
         // add your logic here
     }
     finally
     {
         yourTimer.Enabled = true;// or yourTimer.Start();
     }
}

Tags:

C#

.Net

Timer