Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change label content with timers throwing InvalidOperationException

I'm making an application and I'm using a timer in that application to change label content in WPF C# .NET.

In the timer's elapsed event I'm writing the following code

lblTimer.Content = "hello";

but its throwing an InvalidOperationException and gives a message The calling thread cannot access this object because a different thread owns it.

I'm using .NET framework 3.5 and WPF with C#.

Please help me.
Thanks in advance.

like image 945
necixy Avatar asked Dec 18 '22 01:12

necixy


1 Answers

For .NET 4.0 it is much simpler to use a DispatcherTimer. The eventhandler is then in the UI thread and it can set properties of the control directly.

private DispatcherTimer updateTimer;

private void initTimer
{
     updateTimer = new DispatcherTimer(DispatcherPriority.SystemIdle); 
     updateTimer.Tick += new EventHandler(OnUpdateTimerTick);
     updateTimer.Interval = TimeSpan.FromMilliseconds(1000);
     updateTimer.Start();
}

private void OnUpdateTimerTick(object sender, EventArgs e)
{
    lblTimer.Content = "hello";
}
like image 196
SScott Avatar answered Dec 24 '22 01:12

SScott