Joetjah
Joetjah

Reputation: 6132

Resetting Threading Timer if it's called a second time

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();
}

When I open a certain door, the Timer starts. After 5 seconds, everything closes again.

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?

Upvotes: 8

Views: 7764

Answers (2)

TheNextman
TheNextman

Reputation: 12566

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); 

Upvotes: 15

Nick Hill
Nick Hill

Reputation: 4917

You can do something like this:

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

Upvotes: 7

Related Questions