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

前端 未结 3 1353
面向向阳花
面向向阳花 2020-11-30 12:11

Background: I have a timer that I am using to keep track of how long it has been since the serialPort DataReceived event has been fired. I am creating my ow

相关标签:
3条回答
  • 2020-11-30 13:01

    Had the same problem and after some trying ended up with timer object to null and replace the timer variable it with a new timer object fixed the issue. I know its heavy of resources. But it solves the problem.

    0 讨论(0)
  • 2020-11-30 13:04

    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
    
    0 讨论(0)
  • 2020-11-30 13:09

    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();
         }
    }
    
    0 讨论(0)
提交回复
热议问题