views:

75

answers:

3

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

A: 

Use a Timer. It's there, specifically for that purpose, so why wouldn't you use it?

Joey
+3  A: 

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:

  • You require a STA thread (all ThreadPool threads are MTA)
  • You require that all occurrences of your repeated task run on the same thread
  • You want to assign a particular priority (lower or higher) to your tasks
  • Your tasks are particularly long-running or utilize non-trivial blocks
Adam Robinson
A: 

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.

Bernhard Hofmann