欢迎,欢迎,热烈欢迎。。。

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/

posted @ 2014-12-25 00:46  奇葩史  阅读(4090)  评论(0编辑  收藏  举报
Come On! 不要走。。。