跳到主要內容

如何透過非 UI thread 去存取WPF control


如果把產生資料的邏輯交給UI thread去處理
則有可能會因為處理的資料量太大造成UI hang on的問題
因此我們可以創建另一個thread去幫我們做這件事情

System.Threading.Thread thread = new System.Threading. Thread(() => GenerateDataAndUpdateUI(this));
thread.Start();

可是在update UI control 時
必須使用 Dispatcher 物件來通知 UI thread 去做更新

 
GenerateDataAndUpdateUI(){
             
                //generate data ... 

               Dispatcher.BeginInvoke(newAction(() => {
                   
                                     //update UI ...
                }));

}

否則可能會遇到以下的runtime exception


The calling thread cannot access this object because a different thread owns it

留言