Friday, August 1, 2008

The Case of the 3 Timers

When you ask a Windows Forms developer about the Timer class, you'll get to hear all about the glories of the System.Windows.Forms.Timer class. A Windows Service developer will go on and on and on about the System.Timers.Time. Finally, the fresh graduate who read about the Timer class in .NET will tell you about the System.Threading.Timer class. There are three different classes with each having a purpose of it's own.

System.Windows.Forms.Timer

This is the timer class most Windows Forms application developers would use. The handler code executes within the same thread as the form within which it is placed via the WM_TIMER window message.

The downside of using this class is that it will be unable to raise events while the User Interface thread is busy, such as when calling Thread.Sleep.

System.Timers.Timer

This timer class is included in the components toolbox. It cannot access Windows Forms controls directly and provides a SynchronizingObject property which you can set to an instance of the form to run the handler code in the same thread on which the form instance was created.

Unlike the System.Windows.Forms.Timer class, this class is able to queue events for execution.

System.Threading.Timer

For a light-weight timer class, the System.Threading.Timer class fits the bill. It cannot write to Windows Forms controls so you would have to use the BeginInvoke method of the form for any interaction with the U.I. For writing re-usable code, you can check the InvokeRequired property - if true, you would have to use BeginInvoke.

The members of this timer class are not thread-safe, which is odd considering that it resides within the System.Threading namespace.

No comments: