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:
_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.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?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?答案 0 :(得分:0)
I have discovered a few things after doing some further research.
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.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.