本文介绍了如果第二次调用,则重置线程计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个系统,在该系统中,发生触发器的门会打开 5 秒钟,然后再次关闭.我为此使用 Threading.Timer,使用:
I'm trying to create a system where a trigger happens so doors open for 5 seconds, and then close again. I'm using Threading.Timer for this, using:
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 秒后,一切再次关闭.
When I open a certain door, the Timer starts. After 5 seconds, everything closes again.
但是当我打开某扇门时,等待 2 秒钟,然后再打开另一扇门,3 秒钟后一切都会关闭.如何重置"计时器?
But when I open a certain door, wait 2 seconds, then open another door, everything closes after 3 seconds. How can I 'reset' the Timer?
推荐答案
不要设置定时器,每次开门就改,比如
Do not dispose the timer, just change it every time you open a door, e.g.
// Trigger again in 5 seconds. Pass -1 as second param to prevent periodic triggering.
_timer.Change(5000, -1);
这篇关于如果第二次调用,则重置线程计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!