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?
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:
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:
And lastly, instead of rudely throwing an exception, it may be preferable to just stop the timer: