计时器线程是否等待,直到回调函数中的所有步骤完成,或者在每个周期中都重新调用了回调函数 [英] does the timer thread wait till all the steps in the callback function are done or does the callback function get reinvoked in every period
问题描述
我有一个计时器线程功能
I have a timer thread function
SampleTimer = new Timer(SomeTask,0,70000)
回叫功能如下
void SomeTask(object o)
{
//block using autoresetevent
}
问题在于,即使仍未完成回调方法中的所有操作,SomeTask()回调方法也会每70秒调用一次. 如何阻止计时器在其中所有步骤完成之前调用SomeTask()函数
The issue is the SomeTask() callback method gets called every 70 secs even though all the operations in the callback method is still not done. How can I prevent the timer from calling the SomeTask() function before all the steps within it are completed
推荐答案
我假设您使用的是System.Threading.Timer
.
一种方法是一次性创建计时器,然后在线程完成其任务后重新启动计时器.这样,您可以确定不会有任何重叠:
One way to do it is to create the timer as a one-shot, and then restart it after the thread has completed its task. That way you're certain that you won't have any overlap:
myTimer = new Timer(someMethod, null, 70000, Timeout.Infinite);
在您的回调中:
void TimerCallback(object o)
{
// do stuff here
// then change the timer
myTimer.Change(70000, Timeout.Infinite);
}
在该时间段内指定Timeout.Infinite
会禁用周期性的信号发送,从而将计时器变为单发.
Specifying Timeout.Infinite
for the period disables periodic signaling, turning the timer into a one-shot.
另一种方法是使用监视器:
Another way is to use a monitor:
object TimerLock = new object();
void TimerCallback(object o)
{
if (!Monitor.TryEnter(TimerLock))
{
// already in timer. Exit.
return;
}
// do stuff
// then release the lock
Monitor.Exit(TimerLock);
}
如果您想知道为什么我不使用try/finally
作为锁,请参阅Eric Lippert的博客,
If you're wondering why I don't use a try/finally
for the lock, see Eric Lippert's blog, Locks and exceptions do not mix.
这两种方法的主要区别在于,在第一种方法中,计时器将在上一次回调执行完成后的70秒内触发.计时器将在第二秒内触发70秒,因此下一个回调可能在上一个完成后的任何时间执行,从一秒后到70秒后.
The primary difference in these two approaches is that in the first the timer will fire 70 seconds after the previous callback execution finishes. In the second the timer will fire on a 70 second period, so the next callback might execute any time after the previous one finishes, from one second later to 70 seconds later.
对于我所做的大多数事情,我展示的第一种技术似乎效果更好.
For most things I've done, the first technique I showed seems to work better.
这篇关于计时器线程是否等待,直到回调函数中的所有步骤完成,或者在每个周期中都重新调用了回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!