Hi,
What is the best approach in using a timer. Use a System.Timer.Timer class or use a single Thread in a non-terminating loop with a Thread.Sleep statement?
Thanks in advance
Hi,
What is the best approach in using a timer. Use a System.Timer.Timer class or use a single Thread in a non-terminating loop with a Thread.Sleep statement?
Thanks in advance
Use a Timer. It's there, specifically for that purpose, so why wouldn't you use it?
In general, use the components that are already there if they serve your needs. However, System.Threading.Timer
uses the .NET thread pool, so any of the following conditions would make it a poor candidate:
ThreadPool
threads are MTA)The two methods you refer to are used for different results.
Timers will fire the event and invoke your method on a scheduled interval. They could invoke your method whilst another instance of it is running unless you stop the timer at the start of your processing (DoWork) and start it again when you're done (but then you might miss the timed events).
A method that loops and sleeps will not be invoked when it's busy. The "advantage" here is that you can DoWork, then find that the next timer event has already passed and DoWork immediately again. The alternative is that you have rest periods where you sleep a specified amount of time regardless of how long your DoWork method took.