Outlining Three System Timers
I have seen a few samples of code involving the three timer classes provided with the .Net framework over the years. Juval has such a sample, which he is updating to use . I decided to put together a table that outlines the characteristics of all three. ISynchronizeInvoke.InvokeRequired <code>. Even within the MSDN documentation, however, I have never seen much guidance between when to use </code> System.Threading.Timer <code> and </code> System.Timers.Timer
| Feature description | System.Timers.Timer | System.Threading.Timer | System.Windows.Forms.Timer |
| Support for adding and removing listeners after the timer is instantiated. | Yes | No | Yes |
| Supports call backs on the user-interface thread | Yes | No | Yes |
| Calls back from threads obtained from the thread pool | Yes | Yes | No |
| Supports drag-and-drop in the Windows Forms Designer | Yes | No | Yes |
| Suitable for running in a server multi-threaded environment | Yes | Yes | No |
| Includes support for passing arbitrary state from the timer initialization to the callback. | No | Yes | No |
| Implements IDisposable | Yes | Yes | Yes |
| Supports one-off callbacks as well as periodic repeating callbacks | Yes | Yes | Yes |
| Accessible across application domain boundaries | Yes | Yes | Yes |
| Supports IComponent – hostable in an IContainer | Yes | No | Yes |
Using the by default, simply because it is a slightly lighter weight implementation. System.Windows.Forms.Timer <code> is a relatively obvious choice for user interface programming. Choosing between the other two options is less obvious and generally the choice between the two is insignificant. If hosting within an </code> IContainer <code> is necessary then obviously </code> System.Timers.Timer <code> is the right choice. However, if no specific </code> System.Timers.Timer <code> feature is required, then I suggest choosing </code> System.Threading.Timer
UPDATE – October 5, 2005
Thanks to Stephen Toub for pointing out that , there is support for calling back on the UI thread. System.Timers.Timer <code> can be used in the Windows Forms designer (although it does not appear in the toolbox by default) and that, using </code> SynchronizationObject <code>, on </code> System.Timers.Timer
Comments are closed.