Behavior of AutoReset in Timers.Timer

时间:2018-09-18 19:31:11

标签: .net vb.net timer

I have a timer that I have tied to the behavior of a UI element such that the UI element should auto-hide itself after 30s. After that point, it should only be made visible by explicitly calling Show on the element. I have implemented like this:

Private Sub myBtn_VisibleChanged(sender As Object, e As EventArgs)
    _myBtn.Enabled = True
    _myTmr.Start()
End Sub

Private Sub myTmr_Elapsed(sender As Object, e As EventArgs)
    _myBtn.Hide()
    _myBtn.Enabled = False
    _myTmr.Stop()
End Sub

_myBtn has the VisibleChanged event handled by the above method and _myTmr is setup this way:

Dim _myTmr As System.Timers.Timer = New System.Timers.Timer(30000.0)
_myTmr.AutoReset = False
_myTmr.Enabled = False
AddHandler _myTmr.Elapsed, AddressOf myTmr_Elapsed

I have a few questions about this setup:

  1. Do I need to set _myTmr.Enabled to False on initialization or is that the default behavior? I'm unsure about this and I was unable to track down documentation that elucidated on this point.
  2. How does the AutoReset property work? Does setting it to False mean that, Elapsed will only be raised once? After that happens, what will the value of the timer be? Will calling Start on _myTmr again, cause Elapsed to be raised again?
  3. It appears that myTmr_Elapsed throws an InvalidOperationException because the Elapsed event is raised from a different thread than the UI thread. Is there a way to call Hide on the UI thread?

1 个答案:

答案 0 :(得分:0)

I have discovered a few things after doing some further research.

  1. I shouldn't be using System.Timers.Timer for forms because it will not operate on the UI thread so any UI work that needs to be tied to the timer's Elapsed event will throw an InvalidOperationException. Rather, System.Windows.Forms.Timer should be used.
  2. As I discovered here, setting Enabled to true will reset the timer, so claling Start should do so as well. Since the Windows.Forms.Timer has no AutoReset property, its behavior is somewhat mute at this point.
相关问题