How to change label content with timers throwing InvalidOperationException

◇◆丶佛笑我妖孽 提交于 2020-08-27 19:40:44

问题


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.


回答1:


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";
}



回答2:


InvokeRequired doesn't work in wpf.

The proper way the update a GUI element owned by another thread is this :

Declare this on module level :

delegate void updateLabelCallback(string tekst);

This is the method to update your label :

private void UpdateLabel(string tekst)
    {
        if (label.Dispatcher.CheckAccess() == false)
        {
            updateLabelCallback uCallBack = new updateLabelCallback(UpdateLabel);
            this.Dispatcher.Invoke(uCallBack, tekst);
        }
        else
        { 
    //update your label here
        }
     }


来源:https://stackoverflow.com/questions/2711601/how-to-change-label-content-with-timers-throwing-invalidoperationexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!