简体   繁体   中英

what is the best approach for implementing a thread timer

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM