views:

440

answers:

2

I've got a little problem using WPF Dispatcher Timer. On each timer tick my application freezes for a moment (until timer tick method finishes). This is my code:

private DispatcherTimer _Timer = new DispatcherTimer();

_Timer.Tick += new EventHandler(_DoLoop);
_Timer.Interval = TimeSpan.FromMilliseconds(1500);
_Timer.Start();

Is there any way to avoid this and have my application run smoothly?

+1  A: 

This is expected. your _DoLoop is executed on the same thread as UI.

from DispatcherTimer Class MSDN

If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.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 System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

If you need to execute time consuming computations run it on another thread to keep UI responsive.

majocha
Running it on other thread means I won't be able to change the UI from it without Invoking UI's dispatcher?
Nebo
"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."
majocha
If you don't want to multithread experimenting with DispatcherPriority and breaking your task into smaller methods scheduled separately could also help.
majocha
A: 

create a new thread for _DoLoop,

steven