Comparing Timer with DispatcherTimer

Windows.Forms.Timer uses the windows forms message loop to process timer events. It should be used when writing timing events that are being used in Windows Forms applications, and you want the timer to fire on the main UI thread.

DispatcherTimer is the WPF timing mechanism. It should be used when you want to handle timing in a similar manner (although this isn't limited to a single thread - each thread has its own dispatcher) and you're using WPF. It fires the event on the same thread as the Dispatcher.

In general, WPF == DispatcherTimer and Windows Forms == Forms.Timer.

That being said, there is also System.Threading.Timer, which is a timer class that fires on a separate thread. This is good for purely numerical timing, where you're not trying to update the UI, etc.


I've found good article about timers with small examples here: http://www.progware.org/Blog/post/Timers-in-WPF.aspx

As a conclusion:

If DoSomething() manipulates GUI components then with the Timer you need to use: this.Dispatcher.Invoke((Action)delegate { //GUI RELATED CODE HERE} since you cannot access GUI controls from a different thread directly. With DispatcherTimer you do not need to do that.

If DoSomething() performas a time-consuming task, then the GUI will freeze in the case of the DispatcherTimer. In the case of the Timer it won't since the long methos is executed in a different thread

Tags:

C#

Timer