Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions in callback method for Timers

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.

like image 636
Kornelije Petak Avatar asked Nov 11 '09 22:11

Kornelije Petak


People also ask

What is a timer callback?

Timer(TimerCallback) Initializes a new instance of the Timer class with an infinite period and an infinite due time, using the newly created Timer object as the state object.

What is the point of throwing exceptions?

The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown.


1 Answers

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.

like image 121
SLaks Avatar answered Sep 28 '22 02:09

SLaks