I'm using a System.Timers.Timer in a service that seems to keep ticking after it has been disabled. I'm using autoreset = false so I would expect it to only tick once unless I start it up again. I'm calling stop again, just for good measure, but the timer keeps on ti开发者_JS百科cking. I'm using VB.NET in .net 1.1 and don't have the option to change frameworks.
Here is a simple console app to reproduce the issue. This is not the actual code from the project. I believe the interval is long enought to prevent any thread issues in raising the event multiple times, but I will admit I'm not a threading expert.
Module Module1
Private Timer As New System.Timers.Timer(10000)
Sub Main()
AddHandler Timer.Elapsed, AddressOf Timer_Elapsed
Timer.AutoReset = False
Timer.Start()
While True
Console.ReadLine()
Console.WriteLine("Timer Enabled: " & Timer.Enabled)
End While
End Sub
Private Sub Timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Console.WriteLine("Timer Tick")
Timer.Interval = 15000
Timer.Stop() 'using timer.enabled = false here nets the same effect
End Sub
End Module
You can see that the timer will keep on outputting to console indefinitely even after being stopped. You can press enter to check the value of the timer enabled to confirm that it is false while it is still ticking. It has something to do with the interval being reset after it has ticked, but I don't understand why it isn't showing as enabled if setting the interval is supposed to turn it back on and why calling stop afterwards doesn't stop it.
I'm sure I'm just missing something simple, so any insight would be appreciated.
Update
It seems that it is the combination of autoreset=false and resetting the interval after the tick. If I set autoreset=true, resetting the interval doesn't cause problems. If I take out the interval reset, autoreset=false functions properly. I've tested this in .net 4 and the issue exists there as well. I've got a workaround for my project by using autoreset=true and manually turning off the timer immediately after elapsed, but I would really be interested to find out why exactly it works this way.
When using the Elapsed event, you should set the Timer.Enabled property to false to disable the timer.
You might also read through this thread.
Which .Net Timer() to use
I've had mixed results with System.Timers.Timer, the Windows.Forms.Timer seems to work much more intuitively.
精彩评论