【问题标题】:How to anychronously update a WPF control with results of long running calculation [duplicate]如何使用长时间运行的计算结果随时更新 WPF 控件 [重复]
【发布时间】:2021-05-24 13:47:53
【问题描述】:

我有一个 wpf 控件,一个图表,用户可以在其中与鼠标进行交互。

现在,每次鼠标移动时,我都会进行大量时间计算,大约需要 700 毫秒(即使经过一堆性能评估)。结果应显示在标签内。

所以我想要做的是,当鼠标移动而不是立即更新标签时(然后 UI 滞后近一秒钟),我想做这个异步并在计算完成时更新标签.

怎么做?

【问题讨论】:

标签: c# wpf asynchronous


【解决方案1】:

最简单的方法是为控件设置一个异步事件处理程序,使用Task.Run() 之类的方法在另一个线程上执行 CPU 繁重的工作,并在完成后更新标签。这样的事情会起作用:

private async void Control_Event(object sender, EventArgs e)
{
    var result = await Task.Run(() => MyExpensiveCalculation());
    label.Text = result;
}

private string MyExpensiveCalculation()
{
    //Do your expensive calculation here and return the result.
}

请注意,Task.Run() 应该从 UI 线程调用。 It should not be a part of the calculation implementation.

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多