WPF線程(Step1)——Dispatcher


使用WPF開發時經常會遇上自己建立的線程需要更新界面UI內容,從而導致的跨線程問題。

異常內容:

異常類型:System.InvalidOperationException

異常描述:

“System.InvalidOperationException”類型的未經處理的異常在 WindowsBase.dll 中發生

其他信息: 調用線程無法訪問此對象,因為另一個線程擁有該對象。

ThreadError

在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);
}

 


項目托管地址:https://wpfthread.codeplex.com/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM