开发者

C# WPF project, how to avoid InvalidOperationException?

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜