开发者

C# WPF project, how to avoid InvalidOperationException?

开发者 https://www.devze.com 2022-12-21 18:48 出处:网络
We have a WPF project. I got the following error: InvalidOperationException was unhandled The calling thread cannot access this object because a different thread owns it.

We have a WPF project. I got the following error:

InvalidOperationException was unhandled
The calling thread cannot access this object because a different thread owns it.

I try to get value from a TextBox from a worker thread created by me.

How to avoid this. I was able to avoid this in another Form project by using delegate call back and Invoked() method but somehow it doesn't work in this WPF project.开发者_如何学JAVA

any simple sample code? thanks,


You need to use the Dispatcher to handle this. Instead of using Control.Invoke like in Windows Forms, you now need to use Dispatcher.Invoke or Dispatcher.BeginInvoke to marshal your call back onto the UI thread.


How about something along the lines of:

        if (!Dispatcher.CheckAccess()) 
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            (MyDelegate)delegate
            {
                // Get value
            });
        } 
        else 
        { 
            // Get value
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消