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

我正在尝试创建一个触发器发生的系统,使门打开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秒后关闭。 如何“重置”定时器?

您可以在每次打开门时更换计时器,例如

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

你可以这样做:

 // 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"); }