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 eve
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.
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.
I dont know if it is a best solution, but what I did was a small workaround. My calling thread has subscribed to an event for catching exceptions from across the threads. So when exception occurs in some thread, say in TimerElapsed event, then form the catch block I raise the event passing exception object as an argument to the event.
EventHolderCallingClass: It must define delegate and event as shown below.
public class EventHolderCallingClass
{
public delegate void HandleExceptionEventDelegate(Exception exception);
public event HandleExceptionEventDelegate HandleExceptionEvent ;
void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
//some operation which caused exception.
}
catch(Exception exception)
{
if(HandleExceptionEvent!=null)
HandleExceptionEvent(exception)
}
}
}
Event Handler Class (Exception Handler):
public EventHandlerClassConstructor()
{
EventHolderCallingClass.HandleExceptionEvent += new EventHolderCallingClass.HandleExceptionEventDelegate(HandleExceptionEventHandler);
}
void HandleExceptionEventHandler(Exception exception)
{
//handle exception here.
}
From my humble test under windows 10 framework 4.6, the thread used by the SystemTimers.Timer elapsed event will not propagate the unhandled exception. I needed to fire a event to the main thread to notify the unhandled exception happened.