如何使用抛出InvalidOperationException的计时器更改标签内容

nec*_*ixy 4 .net c# wpf multithreading timer

我正在创建一个应用程序,我正在该应用程序中使用计时器来更改WPF C#.NET中的标签内容.

在计时器已过去的事件中,我正在编写以下代码

lblTimer.Content = "hello";
Run Code Online (Sandbox Code Playgroud)

但它抛出一个InvalidOperationException并给出一条消息调用线程无法访问此对象,因为另一个线程拥有它.

我正在使用.NET framework 3.5和WPF与C#.

请帮我.
提前致谢.

小智 11

对于.NET 4.0,使用DispatcherTimer要简单得多.然后,事件处理程序在UI线程中,它可以直接设置控件的属性.

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";
}
Run Code Online (Sandbox Code Playgroud)