Timer fires inconsistantely

D

derSchweiz

I have an application that requires the use of a timer and I have created
the timer object globally:

Private t As New System.Timers.Timer(4000)

And I have a button that that triggers an event handler:


Private Sub myButton(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
t.Enabled = True
AddHandler t.Elapsed, AddressOf TimerFired
End Sub

Which triggers:

Private Sub TimerFired(ByVal sender As Object, _ByVal e As
System.Timers.ElapsedEventArgs)
MsgBox(commandID)
commandID = commandID + 1

If commandID = 7 Then
t.Enabled = False
t.Stop()
t.Close()
commandID = 0
isFirstStart = False
End If
End Sub

The first the time button gets clicked, the TimerFired method fires every 4
seconds, it works great the first time, however on the second time it goes
like
Fire Fire... 4 seconds.. Fire fire... 4 seconds... fire fire

On the third time it will go like:

fire fire fire... 4 seconds fire fire fire...


How can I make it so that it will go like

fire... 4 seconds... fire... 4 seconds... fire 4 seconds etc...

each time I press the button?

p.s Please explain as simply as possible, this is my first time programming
in VB.

Thanks for any input
 
D

derSchweiz

Looks like I solved my own problem, here's the solution the benifit of
others:
This like of code "AddHandler t.Elapsed, AddressOf TimerFired" should only
be triggered ONCE and only once during the entire execution of the program.
To prevent it from triggering the second time, I simply declared a boolean
variable to be true and then once the button has been triggered once, it
resets the boolean value to false, so it will not recall that line of code,
the handler the second time.
 
C

Cor Ligthert [MVP]

derSchweiz,

Any reason that you don't use the Forms timer? In my expririence does that
with a normal form application give much less problems than the system and
threading timers.

Cor
 
C

Cerebrus

Hi derSchweiz,

Your solution to the problem works, but wouldn't it have been simpler
to wire up the event to the handler outside the Button_Click event ?
Say, in your Sub New() ?

Regards,

Cerebrus.
 
M

Michael D. Ober

Unless you have a specific reason to block the timer from firing, create the
timer "WithEvents" and then use the IDE to create the timer_elapsed handler.
Then you can avoid the AddHandler statement entirely. In the timer
definition, set Enabled =False. Then in your Button handler, simply set the
timer's Enabled property to true.

Mike Ober.
 
D

derSchweiz

My program might not be the most efficient but im just programming for fun
as a hobby, making homebrew applications.

Thanks again for everyone's input!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top