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/

就是爱玩耍,各种玩![‘假’技术‘真’宅]
个人网站:http://www.shisujie.com
原文地址:https://www.cnblogs.com/huaxia283611/p/4183765.html