DispatcherTimer vs a regular Timer in WPF app for a task scheduler DispatcherTimer vs a regular Timer in WPF app for a task scheduler wpf wpf

DispatcherTimer vs a regular Timer in WPF app for a task scheduler


DispatcherTimer is the regular timer. It fires its Tick event on the UI thread, you can do anything you want with the UI. System.Timers.Timer is an asynchronous timer, its Elapsed event runs on a thread pool thread. You have to be very careful in your event handler, you are not allowed to touch any UI component or data-bound variables. And you'll need to use the lock statement where ever you access class members that are also used on the UI thread.

In the linked answer, the Timer class was more appropriate because the OP was trying to run code asynchronously on purpose.


Regular Timer's Tick event is actually fired on the thread where the Timer was created, so in the tick event, in order to access anything with the UI, you will have to go through dispatcher.begininvoke as mentioned below.

RegularTimer_Tick(object sender, EventArgs e){    txtBox1.Text = "count" + i.ToString();     // error can not access    // txtBox1.Text property outside dispatcher thread...    // instead you have to write...    Dispatcher.BeginInvoke( (Action)delegate(){       txtBox1.Text = "count " + i.ToString();    });}

In case of Dispatcher Timer, you can access UI elements without doing begin invoke or invoke as follow...

DispatcherTimer_Tick(object sender, EventArgs e){    txtBox1.Text = "Count " + i.ToString();    // no error here..}

DispatcherTimer just provides convenience over Regular Timer to access UI objects easily.


With .NET 4.5 you can also create an async delegate for your timer if you need to use the new .NET 4.5 await functionality.

        var timer = new DispatcherTimer();        timer.Interval = TimeSpan.FromSeconds(20);        timer.Tick += new EventHandler(async (object s, EventArgs a) =>        {            Message = "Updating...";            await UpdateSystemStatus(false);              Message = "Last updated " + DateTime.Now;                      });        timer.Start();