【问题标题】:Update main UI in WPF between two process runs在两个进程运行之间更新 WPF 中的主 UI
【发布时间】:2013-11-05 03:54:33
【问题描述】:

我在 WPF 中启动了两个背靠背进程,中间有一个 UI 更改。还有一个包含所有内容的while循环。所以,代码看起来像这样:

while(stackpanel.Children.Count != 0)
{
   Grid grid = stackpanel.Children[0] as Grid;

   // start process 1 and WaitForExit()

   stackpanel.Remove(grid);

   // start process 2 and WaitForExit()
}

问题在于,在第一个进程存在之后,第二个进程开始之前,UI 没有更新。它只在 while 循环终止时更新一次。

我怎样才能实现上述逻辑并能够重绘stackpanel?

【问题讨论】:

    标签: wpf process waitforexit


    【解决方案1】:

    在您退出方法之前,您是 waiting on UI thread which won't let refresh your UI。 我强烈建议move your long running process on to seperate thread 等待它,一旦完成,你就可以通过 Dispatcher 回调 UI 线程。

    但是,您可以使用解决方法,只需在 UI 调度程序上排队一个空委托,并将优先级设置为呈现,以便您的 UI 得到刷新 -

       while(stackpanel.Children.Count != 0)
       {
          Grid grid = stackpanel.Children[0] as Grid;
    
          // start process 1 and WaitForExit()
    
          stackpanel.Remove(grid);
    
          Dispatcher.Invoke((Action)(() => { }), DispatcherPriority.Render);
    
          // start process 2 and WaitForExit()
        }
    

    详情请参阅我在here 上的回答。

    【讨论】:

    • 谢谢。用户界面现在正在更新。但是,只有在第二个循环周期结束后才能观察到第一次更新。您还可以发布将长时间运行的进程移动到单独的线程并等待它们的示例代码吗?
    • 请查看 udpate 的回答。从堆栈面板中删除项目后,空委托应在调度程序上排队,以便在 UI 上刷新。
    【解决方案2】:

    您尝试过这些:UpdateLayout() 吗? stackPanel.InvalidateVisual() ?也许是PropertyChanged with String.Empty

    【讨论】:

    • 如果你能发布更多我可以用来运行测试的代码,我可能会提供进一步的帮助......
    猜你喜欢
    • 2013-09-14
    • 2018-08-29
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多