开发者

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开发者_如何学JAVA 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜