旧地址:http://blog.canself.com/thread_dispatcher/
使用WPF开发时经常会遇上自己建立的线程需要更新界面UI内容,从而导致的跨线程问题。
- 异常内容:-
- 异常类型:System.InvalidOperationException
- 异常描述:
1 2 3
| “System.InvalidOperationException”类型的未经处理的异常在 WindowsBase.dll 中发生
其他信息: 调用线程无法访问此对象,因为另一个线程拥有该对象。
|

在WPF中最简便的解决此问题的方法就是使用Dispatcher。
1、最便捷的使用Dispatcher
1 2 3 4 5
| this.Dispatcher.Invoke(new Action(() => { })); Thread.Sleep(100);
|
2、使用控件自身的Dispatcher【在WPF中,控件最后都继承自DispatcherObject】
1 2 3 4 5 6 7 8 9 10 11
| if (!this.pb_test.Dispatcher.CheckAccess()) { this.pb_test.Dispatcher.Invoke( DispatcherPriority.Normal, new UpdateProgressBarDelegate((int progress) => { this.pb_test.Value = progress; }), i); Thread.Sleep(100); }
|
3、同2,利用当前窗体的Dispatcher
1 2 3 4 5 6 7 8 9 10
| if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke( DispatcherPriority.Normal, new UpdateProgressBarDelegate((int progress) => { this.pb_test.Value = progress; }), i); Thread.Sleep(100); }
|