C# 重置线程计时器(如果为');这叫第二次

C# 重置线程计时器(如果为');这叫第二次,c#,timer,C#,Timer,我正在尝试创建一个系统,在这个系统中,会发生一个触发器,使门打开5秒钟,然后再次关闭。我正在使用线程。计时器用于此,使用: OpenDoor(); System.Threading.TimerCallback cb = new System.Threading.TimerCallback(OnTimedEvent); _timer = new System.Threading.Timer(cb, null, 5000, 5000); ... void OnTimedEvent(object ob

我正在尝试创建一个系统,在这个系统中,会发生一个触发器,使门打开5秒钟,然后再次关闭。我正在使用线程。计时器用于此,使用:

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秒钟后一切都会关闭。如何“重置”计时器?

不要处理计时器,只要在每次开门时更改它即可,例如

// Trigger again in 5 seconds. Pass -1 as second param to prevent periodic triggering.
_timer.Change(5000, -1); 

您可以这样做:

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