I read this excellent article Comparing the Timer Classes in the .NET Framework Class Library and came to the conclusion that anything I could do with Windows.Forms.Timer
I can do better with Timers.Timer
- and then some.
So the obvious question that comes to mind is: Why is the Windows.Forms
Timer offered at all?
Legacy (backward compatibility) support?
Other?
Windows.Forms.Timer has designer support. So it behaves like any other Winforms component (i.e. you can drag it onto a form, it's part of the Controls collection, etc).
Timer events raised by
System.Windows.Forms.Timer
class are synchronous with respect to the rest of the code in your Windows Forms app. This means that application code that is executing will never be preempted by an instance of this timer class (assuming you don't callApplication.DoEvents
). Events fired by theWindows.Forms.Timer
class are compatible with your Winform controls; you can safely interact with them without having to callInvoke()
.The
System.Timers.Timer
class is a server-based timer that was designed and optimized for use in multithreaded environments. Instances of this timer class can be safely accessed from multiple threads. AlthoughInvoke()
is technically required to interact with Winforms, the Timer class does provide aSynchronizingObject
property, to which you can attach the Windows form with which you want to safely interact.More here: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
The
Windows.Forms.Timer
events get invoked on the UI thread so you can update the UI from the event handlers directly, which is not normally the case withTimers.Timer
(as you would get cross thread access violation exceptions).And, as @Robert Harvey answered, it also has designer support.
My belief is that it is for winform designer integration, in that you can drag it onto a form, click it and set its properties in the properties pane.
One of advantage of Windows.Forms is that it run in the same thread of GUI and you do not get cross thread exceptions while accessing Form controls.
Well I think the answer is that they are two completely different types of timers. The
Windows.Forms.Timer
is a single-threaded application timer that's well suited for timers existing on the client running application.In contrast the
Timers.Timer
is a server-based timer that is better suited for Windows services.You can find their documentation and read the excerpts and more from Microsoft.
It's not that one should never be used or always used, the serve two different purposes.
The main convenience of the
Windows.Forms.Timer
is that its events are fired on the UI (Winforms) thread. If your timer events perform UI operations, it may be the simplest alternative (instead of callingControl.Invoke/BeginInvoke
orSynchronizationContext.Post/Send
inside all of your events).