我想知道如何在执行Thread.sleep()之前刷新wpf元素。在下面的场景中,首先执行Thread.sleep()调用,然后更新wpf元素。
我试过这个:
在button_click事件处理程序中:
编辑:为了理解我想要什么,我添加了一些变量赋值和注释。
private void button_click(object sender, RoutedEventArgs e){
//fist of all, set the static variable to_change to true, then Update GUI label
to_change = true;
Thread thread = new Thread(UpdateGUI);
thread.Start();
//Then sleep 1 second and ( With label changed)
Thread.Sleep(1000);// one second
//and lately reset the value of to_change to false and update the GUI again
to_change = false;
//UpdateGUI.
}
在UpdateGUI中,我有:
private void UpdateGUI()
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(ThreadStart)delegate()
{
this.label_success.Content = "Successful!";
}
);
}
我也尝试过DispatcherPriority.Send,它是的最高优先级
我想我错过了一些重要的概念。
提前感谢!
您可以通过向Dispatcher调用优先级低于或等于要执行的任务的项目,强制WPF处理其队列中的所有项目。只需传递一个空的委托作为操作,如下所示。
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { }));
这将起作用;然而,这样做不应该是"正常的",我很好奇为什么你需要睡眠你的主UI线程。。。你上面显示的代码很可怕,但我不知道大局,所以也许这是有原因的?