System.Timer的行为时,Interval属性改变 [英] Behaviour of System.Timer when Interval property changed

查看:154
本文介绍了System.Timer的行为时,Interval属性改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个System.Timer设置为每天上午02时触发事件。 如果定时器启动的过程中失败,那么我想计时器 在进程完成之前成功地被重置为运行每隔15分钟。

I have a System.Timer setup to trigger an event every day at 2AM. If the process the timer starts fails then I want the timer to be reset to run every 15 minutes until the process completes succesfully.

// this is how the timer is set up. 
// this is working correctly.

double startTime = milliseconds_of_hour_to_start.

Timer = new System.Timers.Timer( startTime);

下面是code键复位成功的事件处理程序的或失败的定时器。 的计时器不会被停止, 只是Interval属性正在被重置。

Here is the code to reset the timer on success or failure of the event handler. NOTE the timer is not being stopped, just the Interval property is being reset.

if (ProcessSuccess)
{
  Timer.Interval = TimeSpan.FromHours(24).TotalMilliseconds;
}
else
{
  Timer.Interval = TimeSpan.FromMinutes(15).TotalMilliseconds;
}

我的问题是,如果这个过程失败,说4次,然后成功将定时器现在可以在凌晨3点左右运行? 即没有将2AM的原开始时间由15分钟后提前?

My question is this, if the process fails say 4 times, then succeeds will the Timer now be running at around 3AM? i.e. after failing will the original start time of 2AM be advanced by 15 minutes?

推荐答案

我建议您下载反射,你会发现一个快速的答案,这样的问题。计时器的间隔由TimerBase.ChangeTimer()改变。这需要多项措施,以确保间隔更新是安全的,准确的。在code运行在一个finally块,这样即使一个ThreadAbortException不能搞砸了。它获得一个锁(m_lock成员),以确保访问跨线程序列化。该ChangeTimerNative()调用调用到CLR更新本地计时器。该方法是通过TimerNative :: CorChangeTimer()来实现,它调用ChangeTimerQueueTimer()Windows API函数。该函数被记录到安全从经过的回调函数内部调用时也是如此。

I encourage you to download Reflector, you'll find a quick answer to a question like this. The timer's interval is changed by TimerBase.ChangeTimer(). It takes several measures to ensure the interval update is safe and accurate. The code runs in a finally block so that even a ThreadAbortException cannot mess it up. It acquires a lock (m_lock member) to ensure access is serialized across threads. The ChangeTimerNative() call calls into the CLR to update the native timer. That method is implemented by TimerNative::CorChangeTimer(), it invokes the ChangeTimerQueueTimer() Windows API function. That function is documented to be safe even when called from inside the Elapsed callback function.

长话短说,是:它拥有你正在寻找的行为。但是当心不可避免的竞争条件,定时器可能已经过去了,线程池线程,使回调可能已经计划运行,但没有得到执行还有一个机会。获取回调的马上的后更改计时器也不是不可能的。

Long story short, yes: it has the behavior you are looking for. Beware however the inevitable race condition, the timer might already have elapsed and the threadpool thread that makes the callback may have already been scheduled to run but didn't get a chance to run yet. Getting the callback immediately after changing the timer is not impossible.

这篇关于System.Timer的行为时,Interval属性改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆