如果第二次调用线程计时器,则重置线程计时器

时间:2013-06-14 13:04:44

标签: c# timer

我正在尝试创建一个系统,其中触发器发生,因此门打开5秒钟,然后再次关闭。我正在使用Threading.Timer,使用:

OpenDoor();
System.Threading.TimerCallback cb = new System.Threading.TimerCallback(OnTimedEvent);
_timer = new System.Threading.Timer(cb, null, 5000, 5000);
...
void OnTimedEvent(object obj)
{
    _timer.Dispose();
    log.DebugFormat("All doors are closed because of timer");
    CloseDoors();
}

当我打开某扇门时,计时器启动。 5秒后,一切都再次关闭。

但是当我打开某扇门时,等待2秒,然后打开另一扇门,一切都会在3秒后关闭。如何“重置”定时器?

2 个答案:

答案 0 :(得分:10)

每次打开门时都可以更改计时器,例如

mytimer.Change(5000, 0); // reset to 5 seconds

答案 1 :(得分:3)

您可以这样做:

// First off, initialize the timer
_timer = new System.Threading.Timer(OnTimedEvent, null,
    Timeout.Infinite, Timeout.Infinite);

// Then, each time when door opens, start/reset it by changing its dueTime
_timer.Change(5000, Timeout.Infinite);

// And finally stop it in the event handler
void OnTimedEvent(object obj)
{
    _timer.Change(Timeout.Infinite, Timeout.Infinite);
    Console.WriteLine("All doors are closed because of timer");
}