I very strongly urge you not to use System.Timers.Timer
, primarily due to this little bit of information from the Remarks section in the MSDN documentation.
The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event.
Which means that if your timer's elapsed event throws an exception that you don't explicitly catch, the exception will get swallowed and you'll never know that something bad happened.
Consider this Elapsed
event handler:
static void MyTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Console.WriteLine("Badness! Throwing exception");
throw new ApplicationException("something bad happened");
}
Clearly, the intention here is to kill the program immediately because it encountered an unrecoverable error. But the exception will never escape to the main program. The timer handler in .NET does essentially this:
try
{
MyTimer_Elapsed(sender, args);
}
catch
{
// Why would anybody want to know that something bad happened?
}
It's a bug hider and as a result I won't use it.
In addition, there's no way to specify a context object that will be supplied in the event arguments, like there is with the Windows Forms timer (the Tag
property) or System.Threading.Timer
(the state
parameter passed to the constructor).
System.Timers.Timer
is a broken and limited component wrapper around System.Threading.Timer
. Its two conveniences (the component wrapper and the SynchronizingObject
) are far outweighed by its idiotic exception swallowing and the lack of a user context object. Don't use it. Use System.Threading.Timer
instead.