More on Timers in .NET

In a previous post, I mentioned the three types of timers in the .NET Framework. In the comments of that post I had someone ask about the differences in why/when to use the different timers, so I thought I would do a little more research. 

I posted this inquiry to the ALT.NET Google Group and received the following responses:  

Ben Scheirman 

Windows Forms timers are more to update things on the UI.

System.Threading.Timer is for performing timed actions in any .NET code.
For example, say you want to execute a function, but at a later time…
like “Call this method in 10 seconds”.  You can also set it up to execute
some code at a regular interval.

The short answer, use WinForms timer when you’re working on a WinForm, and
use Threading.Timer everywhere else.

Mohammad Azam suggested a great article that goes into great detail by Comparing the Timer Classes in the .NET Framework Class Library.

High point quotes from the article:

[Talking about Windows.Forms.Timer] Just like the rest of the code in a typical Windows Forms application, any code that resides inside a timer event handler (for this type of timer class) is executed using the application’s UI thread. During idle time, the UI thread is also responsible for processing all messages in the application’s Windows message queue.

The System.Timers.Timer class will, by default, call your timer event handler on a worker thread obtained from the common language runtime (CLR) thread pool. This means that the code inside your Elapsed event handler must conform to a golden rule of Win32 programming: an instance of a control should never be accessed from any thread other than the thread that was used to instantiate it.

[Talking about System.Threading.Timer] Instances of this class are not inherently thread safe, given that it resides in the System.Threading namespace. (Obviously, this doesn’t mean it can’t be used in a thread-safe manner.) The programmatic interface of this class is not consistent with the other two timer classes and it’s also a bit more cumbersome.

From reading this article and the replies to my inquiry on the ALT.NET Google Group, it sounds like if your needing a timer for the UI, use System.Windows.Forms.Timer; otherwise, the System.Threading.Timer is the way to go.

^..^

Advertisement

Posted on December 5, 2009, in .NET General, C#. Bookmark the permalink. 1 Comment.

Leave a Reply

Please log in using one of these methods to post your comment:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.