Implementing the .NET DispatcherTimer

Standard

One of the issues with multi-threading in WPF is the inability for processes on a separate thread from the user interface to directly access objects in the UI. The .NET Timer object does not run in the same thread as WPF’s UI, so it therefore cannot directly update the UI. Instead, the Timer must post UI updates to the dispatcher of the UI thread, using the Invoke or BeginInvoke methods. However, an easier method exists for implementing a Timer that updates the UI – the DispatcherTimer.

The DispatcherTimer runs on the same thread as the UI. Therefore, using the DispatcherTimer instead of the traditional Timer object allows UI updating without the need for the Invoke or BeginInvoke methods.

The DispatcherTimer works in almost the same way as the traditional Timer:

  1. Create an instance of the DispatcherTimer
  2. Assign a TimeSpan to the DispatcherTimer’s Interval property
  3. Assign an event handler to the DispatcherTimer’s Tick event
  4. Start the timer

It really is that easy! Let’s take a look at some sample code. All of the following code can be placed in your DataModel. Continue reading