Timeout for System.Timers.Timer and exception throwing

645 Views Asked by At

I'm using a .NET System Timer to do some actions in a regular interval.

Is there a way to make the timer stop working after a defined time somehow in its definition? Or do I have to use a second timer which will stop the first?

Also, when the timeout hits, I want to throw an exception. It's my understanding that System.Timers.Timer silently swallows the exception. How can I throw the exception to the invoking thread which created the timer?

1

There are 1 best solutions below

5
Fildor On

If you insist on keeping a timer to do this, you could compute a dead-line when starting the timer and check that deadline in each tick:

// inside Tick-handler method
if( DateTime.Now > _deadline ) throw new TimerShouldDieException();

However if you want to inform some other entity that this happened, throwing an Exception won't be enough. In that case, you maybe want to fire an event:

// inside Tick-handler method
if( DateTime.Now > _deadline )
{
     OnTimerExpired(_timer);
     throw new TimerShouldDieException();
}

And lastly, instead of rudely throwing an exception, it may be preferable to just stop the timer:

// inside Tick-handler method
if( DateTime.Now > _deadline )
{
     _timer.Stop(); // Assuming you have a class field for this timer named "_timer";
     OnTimerExpired(_timer);
}