【问题标题】:C#/WPF Using async and await but the UI thread is still blockedC#/WPF 使用 async 和 await 但 UI 线程仍然被阻塞
【发布时间】:2012-06-11 16:01:15
【问题描述】:

我有这个简单的代码:

private async void Button_Click_2(object sender, RoutedEventArgs e)
{
    var progress = new Progress<int>();

    progress.ProgressChanged += (a, b) =>
    {
        this.progressBar.Value = b;
    };

    // this is blocking
    await this.LongRunOpAsync(filepath, progress);

    // this is not blocking
    // await this.LongRunOpAsync(filepath, null);
}

public Task LongRunOpAsync(string filename, IProgress<int> progress)
{
    return Task.Run(() =>
    {
        using (var ops = new LongOps())
        {
            ops.LongRunOp(filename, progress);
        }
    });
}

单击按钮后,UI 仍然无法长时间运行。如果我不使用 Progress 而是将长时间运行的操作 null 作为第二个参数,则 UI 不会阻塞。我很确定这个“错误”是由于我对 async/await 和线程的一些误解。

【问题讨论】:

  • 我认为你需要在 LongRunOpAsync 方法中使用 async 和 await ,而不是在按钮点击中。

标签: c# user-interface asynchronous async-await


【解决方案1】:

您显示的代码不会阻塞 UI 线程。
事实上,如图所示,它不需要 async/await - 所以我假设这不是实际代码。

您需要查看ops.LongRunOpprogress 函数的作用。

我怀疑它会将progress 编组回 UI 线程——因此它可以访问 UI 控件。
如果它过于频繁且过快地执行此操作,它将淹没 UI 线程并使应用程序无响应。

【讨论】:

  • 这是真的。 ops.LongRunOp 经常报告这似乎是实际问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
相关资源
最近更新 更多