使用WPF開發時經常會遇上自己建立的線程需要更新界面UI內容,從而導致的跨線程問題。
異常內容:
異常類型:System.InvalidOperationException
異常描述:
“System.InvalidOperationException”類型的未經處理的異常在 WindowsBase.dll 中發生
其他信息: 調用線程無法訪問此對象,因為另一個線程擁有該對象。
在WPF中最簡便的解決此問題的方法就是使用Dispatcher。
1、最便捷的使用Dispatcher
this.Dispatcher.Invoke(new Action(() => { //Do Something //更新UI操作 })); Thread.Sleep(100);
2、使用控件自身的Dispatcher【在WPF中,控件最后都繼承自DispatcherObject】
if (!this.pb_test.Dispatcher.CheckAccess()) { //更新UI界面 this.pb_test.Dispatcher.Invoke( DispatcherPriority.Normal, new UpdateProgressBarDelegate((int progress) => { this.pb_test.Value = progress; }), i); Thread.Sleep(100); }
3、同2,利用當前窗體的Dispatcher
if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke( DispatcherPriority.Normal, new UpdateProgressBarDelegate((int progress) => { this.pb_test.Value = progress; }), i); Thread.Sleep(100); }