Throwing exceptions in callback method for Timers
Solution 1
The exception is not passed back to the calling thread. If you want it to be, you can add a catch
block and figure out a way to signal the calling thread. If the calling thread is a WinForms or WPF UI thread, you can use the SynchronizationContext
class to pass a call to the UI thread. Otherwise, you could use a thread-safe queue (or a sync lock) and check it periodically in the other thread.
System.Timers.Timer
will silently swallow exceptions and continue the timer (although this is subject to change in future versions of the framework); System.Threading.Timer
will terminate the program.
Solution 2
I don't know what the best option is, but when I'm using a callback timer I'm normally throwing exceptions and letting them bubble up to the main callback routine, where I handle them gracefully. The thread continues to run on the timer as it should.
Unhandled exceptions in the thread (System.Threading.Timer) will stop your entire program.
Kornelije Petak
EDU: MSc.IT @ Faculty of Electrical Engineering and Computing, University of Zagreb, Croatia
Updated on June 02, 2022Comments
-
Kornelije Petak almost 2 years
I was unable to find an answer to this question anywhere...
What happens with the exceptions thrown in the callback method for System.Threading.Timer, (or in the event handler for System.Timers.Timer). Is the exception propagated to the thread on which the timer was created or is the exception lost?
What are the side-effects of throwing an exception within the timer's callback functions?
What would be the right way to signalize to the timer's creation thread that the exception in the worker thread (callback method) has been thrown?
Thanks for your time.