Wednesday, December 15, 2010

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 theDispatcher 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 becauseDispatcherTimer 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 aDispatcherTimer 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:
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(100);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();

Above is from: http://code.dortikum.net/2008/08/06/timer-vs-dispatchertimer-in-wpf/

An Example of DispatcherTimer


private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DispatcherTimer dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    dispatcherTimer.Start();
}

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    listBox1.Items.Add(DateTime.Now.Hour.ToString() + ":" +
        DateTime.Now.Second.ToString());
   
    CommandManager.InvalidateRequerySuggested();
    listBox1.Items.MoveCurrentToLast();
    listBox1.SelectedItem = listBox1.Items.CurrentItem;
    listBox1.ScrollIntoView(listBox1.Items.CurrentItem);
}

1 comment: