WPF - 同步 UI 更新

发布于 2024-11-26 16:50:27 字数 810 浏览 2 评论 0原文

如果我理解正确,则更改 WPF 中的任何控件(例如标签的文本)会将更新排入调度程序中。调度程序等待我的代码完成,当有时间时它会处理整个队列。

为此,调用

double  current = 0;
ReportProgress (0d, "ProcessingStarted");
foreach (var item in collection)
{
        item.Process(); //takes about 10s
        current++;
        ReportProgress (current / (double)collection.Count, "Processing item No. " + current.ToString () + " finished");
}
ReportProgress (1d, "Finished");

ReportProgress 调用带有此事件处理程序的事件时

private void handlerProgressMade (object sender, ProgressEventArgs e)
{
    pbProgress.Value = pbProgress.Maximum * e.Percent;
    lbProgressMessage.Content = e.Message;
}

,最终会显示完整的进度条和消息“已完成”,但不会显示步骤间。

我知道这可以通过在不同线程中调用函数并异步更新 UI 来完成(并且它会在某个时候发生),但目前添加线程似乎是不必要的复杂化。

如何强制Dispatcher立即更新并重绘?

If I understand correctly changing any control in WPF (eg. text of a Label) enqueues an update in Dispatcher. Dispatcher waits for my code to finish and when it has time it processes the whole queue.

For this, calling

double  current = 0;
ReportProgress (0d, "ProcessingStarted");
foreach (var item in collection)
{
        item.Process(); //takes about 10s
        current++;
        ReportProgress (current / (double)collection.Count, "Processing item No. " + current.ToString () + " finished");
}
ReportProgress (1d, "Finished");

where ReportProgress invokes an event with this event handler

private void handlerProgressMade (object sender, ProgressEventArgs e)
{
    pbProgress.Value = pbProgress.Maximum * e.Percent;
    lbProgressMessage.Content = e.Message;
}

ends up with full progressbar and message "Finished" displayed, but the intersteps are not shown.

I am aware that it could be done by calling the function in different thread and updating UI asynchronously (and it is going to happen at some point), but for now adding threads seems like unnecessary complication.

How to force the Dispatcher to update and redraw immediately?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吖咩 2024-12-03 16:50:27

如果您不想使用后台线程,那么在设置进度条值之前和之后,Application.DoEvents() 的旧技巧可能会有所帮助,因为它将等待清除所有堆积的消息队列在 GUI 消息总线中

if you dont want to use background thread, then before and after you set the progress bar value, old hack of Application.DoEvents() might help as it will wait to clear all message queue that got piled up in the GUI Message Bus

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文