看下面的代码:
new Thread(()=> {
Application.Current.Dispatcher.BeginInvoke(new Action(() => {
while (true)
{
Thread.Sleep(1000);
}
}), null);
Console.WriteLine("test");
}).Start();
这段代码,会在控制台打印test,然后界面会一直卡住。界面卡住,说明while循环是在ui线程执行的,能够打印test,说明在执行Application.Current.Dispatcher.BeginInvoke时并没有阻塞当前界面,如果把BeginInvoke改成Invoke,那么test将不会被打印,说明Invoke方法的逻辑是把委托交给ui线程执行,并阻塞当前线程,直到委托结束。而BeginInvoke方法则首先新开一个线程,那新开的线程,再将委托交给ui线程处理。注意,最终执行委托的线程都是ui线程。所以,BeginInvoke由于有个新开线程的过程,不会阻塞当前线程。但仍然会阻塞界面。
另外BeginInvoke是可以指定优先级的,通过方法BeginInvoke(DispatcherPriority, Delegate)来设置优先级。