Throwing exceptions in callback method for Timers Throwing exceptions in callback method for Timers multithreading multithreading

Throwing exceptions in callback method for Timers


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 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.


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.    }