WPF Dispatcher.Invoke和Dispatcher.BeginInvoke执行顺序

Dispatcher.Invoke是同步执行

Dispatcher.Invoke(new Action(() => {
stackPanel.Children.Add(new TextBlock() { Text = "1" });
}));
stackPanel.Children.Add(new TextBlock() { Text = "2" });
stackPanel.Children.Add(new TextBlock() { Text = "2" });
stackPanel.Children.Add(new TextBlock() { Text = "2" });
stackPanel.Children.Add(new TextBlock() { Text = "2" });

结果:

 

 

 Dispatcher.Invoke是异步执行,执行的顺序是当前子线程执行完毕后再执行BeginInvoke中的代码

Dispatcher.BeginInvoke(new Action(() => {
stackPanel.Children.Add(new TextBlock() { Text = "1| "+ DateTime.Now.ToString("mm:ss fff") });
}));
stackPanel.Children.Add(new TextBlock() { Text = "2| " + DateTime.Now.ToString("mm:ss fff") });
stackPanel.Children.Add(new TextBlock() { Text = "2| " + DateTime.Now.ToString("mm:ss fff") });
stackPanel.Children.Add(new TextBlock() { Text = "2| " + DateTime.Now.ToString("mm:ss fff") });
stackPanel.Children.Add(new TextBlock() { Text = "2| " + DateTime.Now.ToString("mm:ss fff") });
Thread.Sleep(500);

结果:

 

 

可以看到,在等待500毫秒后才开始执行Dispatcher.BeginInvoke

posted @ 2021-11-23 19:08  奇迹之耀  阅读(370)  评论(0编辑  收藏  举报