Best way to stop and restart a 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
 
B

Bob Powell [MVP]

The Timer.Enabled actually destroys the timer internally anyway. The extra
timer event's you're seeing are probably due to messages that are in the
queue. This can happen if you do a lot of processing in the timer tick
handler such as drawing on screen or disc access.

A more accurate and reliable timer can be found in System.Threading. The
dlegate for this timer is called directly and there are never any messages
hanging around in the queue.

--
Bob Powell [MVP]
Visual C#, System.Drawing

The Image Transition Library wraps up and LED style instrumentation is
available in the June of Well Formed for C# or VB programmers
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

The GDI+ FAQ RSS feed: http://www.bobpowell.net/faqfeed.xml
Windows Forms Tips and Tricks RSS: http://www.bobpowell.net/tipstricks.xml
Bob's Blog: http://bobpowelldotnet.blogspot.com/atom.xml
 
U

User

Thanks ,

I tried this System.Threading.Timer. Is it possible that it
automatically create many threads that run the code in the elapsed event?

How can I be sure that I have only one thread under this timer?

Thank you!
 

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