Problem with System.Timers.Timer

U

User

Hi,

What is the best way to release all resources holded by the Timer
(myTimer from class System.Timers.Timer)?

Is it:
1- myTimer.dispose
2- myTimer.enabled = false
3- myTimer.close

I want to have the timer set to nothing so I can recreate a new one, I
want to do this in a second step:

myTimer = New System.Timers.Timer
AddHandler myTimer.Elapsed, AddressOf ListenToRequest
myTimer.Interval = 100
myTimer.Enabled = True

I am asking this because it seem that the timer loop a couple of time
before being stopped, and raising errors by the way.
This is my original code:
myTimer.Dispose()
myTimer = New System.Timers.Timer
AddHandler tmrClientQwery.Elapsed, AddressOf ListenToRequest
myTimer.Interval = 100
myTimer.Enabled = True

Thank you very much
 
G

Guest

I normally set enabled to false first - so that I know that it will not kick again while I then dispose of it. AFAIK close just calls dispose - will have to look at the IL to be sure, however.

HTH
 
G

Guest

Hi User,

That happens because you set that timer to fire every 100 miliseconds. The
Timers.Timer fire Elapse event asyncron. So, and even if you can't see it
that timer fires more times that you think.

The best way to solve that is setting the AutoReset property to False and in
each Elapse event call Start method or set Enabled to True, at the end of
your handling code. Like this you garantee that only one instance of that
event fires at a time. And when you want to stop that timer just call Stop
method or set Enabled property to False.

If your handling code just take more that 100ms to process you will have
several instances of Elapse event handle code running at the same time. This
could be bad depending of what your are doing.

Be aware that the Timer has a bug that is mentioned 'Bug in Timers.Timer'.
Just use my workaround to handle it.

Pedro Gonçalves
 

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