目录

WPF中UI及时更新

目录

不管是在winform还是在WPF中,我们要做一个进度条,用在一个大循环或者一个耗时的处理中,首先想到的就是多线程。否则进度条会出现假死现象,进度条不会更新。做多线程是比较麻烦的,如果只是简单的更新UI,可以用Systems.DoEvents。

在winform中,使用PeekMessage处理完消息队列,使UI有机会更新。在WPF中,可以在Dispatch里使用PushFrame达到同样的效果。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public void DoEvents()
{

	DispatcherFrame frame = new DispatcherFrame();
	Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
	new DispatcherOperationCallback(delegate(object f)
	{


	((DispatcherFrame)f).Continue = false;

		return null;
	}
	), frame);
	Dispatcher.PushFrame(frame);
}

写了这个方法后,我们在循环中或者事件中,在需要更新的UI后面调用一下DoEvents()就可以了。