I am having problems converting my DispatcherTimer syntax to the Thread Timer. When i run my application suddenly it shuts down without any error.
Basically i want the timer to execute 2 methods every 5 seconds.
EDIT: The 2 methods are updating the UI.
I am trying to attempt to get rid of the DispatcherTimer because i have to much freezes and delays in the UI display.
Dispatcher timer code:
timerW = new DispatcherTimer();
timerW.Tick += new EventHandler(timerW_Tick);
timerW.Interval = new TimeSpan(0, 0, 5000);
timerW.Start();
private void timerW_Tick(object sender, EventArgs e)
{
DisplayWegingInfo();
CaculateTimen();
}
Code for the System.Threading Timer:
public void InitializeDispatcherTimerW()
{
TimerCallback callback = MyTimerCallBack;
timerW = new Timer(callback);
timerW.Change(0, 5000);
}
private void MyTimerCallBack(object state)
{
DisplayWegingInfo();
CaculateTime();
}
Thanks.
Judging by the name DisplayWedgingInfo, I would guess this method updates the UI? System.Threading.Timer executes on a thread that is different than the UI thread, so to be able to update the UI from that thread you would need to marshal those calls back to the
Dispatcherthread usingDispatcher::[Begin]Invoke.So you can leave whatever expensive work that doesn’t touch UI elements as is, but for the UI manipulation you would simply do:
I should point out that there will be some interruption to any UI interaction/rendering that might be going on when the invocation does occur. This is unavoidable as the execution will happen on the main thread. By using
DispatcherPriority.Backgroundyou at least schedule the update with a priority that keeps it lower than any input that the user might be providing at the time. However, don’t expect to be able to make a massive update to the UI without any penalty. If you need to do this it’s best to queue up multiple invocations withBackgroundpriority so that they can happen with higher priority stuff like input in between if necessary.