Timer vs. DispatcherTimer in WPF

Have you ever wondered what is the difference between Timer and DispatcherTimer in WPF / Silverlight? In this post I will try to explain you the little difference. Timer generates recurring events in an application. DispatcherTimer is a timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority. Timers are not guaranteed to execute exactly when the time interval occurs, but are guaranteed not to execute before the time interval occurs. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. When the DispatcherTimer operation executes, it is dependent of the other jobs in the queue and their priorities.

If a Timer is used in a WPF application, it is worth noting that the Timer runs on a different thread then the user interface (UI) thread. In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Reasons for using a DispatcherTimer opposed to a Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set.

So, the right way to do schedule operations in WPF / Silverlight application is the following:

8 thoughts on “Timer vs. DispatcherTimer in WPF

  1. […] (Xem thêm so sánh sự khác biệt giữa Timer và DispatcherTimer ở trang timer-vs-dispatchertimer-in-wpf/) […]

  2. Very helpful.
    Thanks.

  3. Do you have any input on dealing with DispaterTimer overload. I am using it to run multiple objects and after about 5 hours or so the CPU reaches 80% and it no longer functions as expected. I’m afraid that they are NOT being reclaimed with the GC.

    Thanks

    • Sorry Ryan, but I have no input on this. What kind of object are you loading? Maybe you should destroy them when they are no longer used in order to free resources.

  4. Grayson Peddie

    I should note that you need to add System.Windows.Threading to the list of “using” imports above your code.

  5. Thanks for the guidance!

    Found some extra info @

    http://www.albahari.com/threading/part3.aspx#_Timers

  6. A Real Developer

    So, copying and pasting the remarks from the MSDN library counts as “explaining” now? Lame. Very lame.

  7. Free Webmaster Guide

    I ran into this page accidentally, surprisingly, this is a amazing blog :-). The site owner has carried out a superb job of putting it together, the info here is really insightful. You just secured yourself a guarenteed reader.