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);

Above is from:

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);

private void dispatcherTimer_Tick(object sender, EventArgs e)
    listBox1.Items.Add(DateTime.Now.Hour.ToString() + ":" +
    listBox1.SelectedItem = listBox1.Items.CurrentItem;

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.