Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing Label content every second WPF

Tags:

c#

wpf

xaml

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?

like image 698
Babak.Abad Avatar asked Sep 15 '13 19:09

Babak.Abad


1 Answers

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.

like image 82
Rohit Vats Avatar answered Sep 23 '22 18:09

Rohit Vats