在WPF應用中,如果遇到多線程的需求時,如果引用WPF控件時會引發異常,異常內容:調用線程無法訪問此對象,因為另一個線程擁有該對象。
WPF 對象是從 DispatcherObject 派生的,這提供了用於處理並發和線程的基本構造。 WPF 基於調度程序實現的消息系統。 其工作方式與常見的 Win32 消息泵非常類似;事實上,WPF 調度程序使用 User32 消息執行跨線程調用。當WPF用戶線程中更新UI時,要通過Dispatcher來進行。
以下是常見的幾種模式:
ViewModel中對UI綁定的數據進行訪問,有的控件不支持MVVM直接在其他線程里操作此控件綁定的對象,會造成線程無法訪問此對象,此方法是異步訪問,不等待返回結果繼續執行后面的代碼
string code = string.Empty; Application.Current.Dispatcher.BeginInvoke(new Action(() => { Line = 2; code = Document.Text; })); evaluation.TaoCodeCompile(code); evaluation.Execute();
如果想要同步訪問改為Invoke即可
Application.Current.Dispatcher.Invoke(new Action(() => { Line = 2; code = Document.Text; })); evaluation.TaoCodeCompile(code); evaluation.Execute();
在View.xmal.cs里如果需要跨線程訪問時可以使用
string code = string.Empty; Dispatcher.Invoke(() => { code = PART_TextEditor.Document.Text; });
如果想要異步訪問改為BeginInvoke即可
string code = string.Empty; Dispatcher.BeginInvoke(() => { code = PART_TextEditor.Document.Text; });