[英]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? 使用System.Timer.Timer类还是在非终止循环中使用Thread.Sleep语句使用单个Thread?
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: 但是, System.Threading.Timer
使用.NET线程池,因此以下任何一种情况都将使其不适合使用:
ThreadPool
threads are MTA) 您需要一个STA线程(所有ThreadPool
线程都是MTA) 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). 他们可以在另一个实例正在运行时调用您的方法,除非您在处理开始时停止计时器(DoWork),然后在完成后再次启动它(但是这样您可能会错过定时事件)。
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. 这里的“优势”是您可以执行DoWork,然后发现下一个计时器事件已经过去,并且立即再次执行DoWork。 The alternative is that you have rest periods where you sleep a specified amount of time regardless of how long your DoWork method took. 另一种选择是,无论您的DoWork方法花费了多长时间,您都会有一段休息时间,在这段时间内您会睡一段指定的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.