I'm trying to refresh a label content every second. So I define two methods as below. I use startStatusBarTimer()
in my constructor of Window
.
codes:
private void startStatusBarTimer()
{
System.Timers.Timer statusTime = new System.Timers.Timer();
statusTime.Interval = 1000;
statusTime.Elapsed += new System.Timers.ElapsedEventHandler(statusTimeElapsed);
statusTime.Enabled = true;
}
private void statusTimeElapsed(object sender, ElapsedEventArgs e)
{
lblNow.Content = DateTime.Now.ToString("yyyy/MM/dd");
}
But I get this error:
The calling thread cannot access this object because a different thread owns it.
What is wrong? Or What can I do?
You are facing thread affinity issue. Since elapsed event is called on background thread
, you cannot access UI controls from background thread. You need to put your action on UI dispatcher
so that it gets dispatch to UI thread -
private void statusTimeElapsed(object sender, ElapsedEventArgs e)
{
App.Current.Dispatcher.Invoke((Action)delegate
{
lblNow.Content = DateTime.Now.ToString("yyyy/MM/dd");
});
}
OR
You can use DispatcherTimer
which is built specially for this purpose. You can access UI controls from its Tick
event handler. Refer to the sample here at MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With