【问题标题】:We need to have "double" await so that GUI will not freeze?我们需要“双重”等待,以便 GUI 不会冻结?
【发布时间】:2012-10-18 03:50:45
【问题描述】:

我希望我的 GUI 在阅读 Asynchronous Programming with Async and Await (C# and Visual Basic) 后不会挂起

    public async Task<string> DoBusyJob()
    {
        // Busy Job
        Thread.Sleep(10000);
        i++;
        return "Finished " + i;
    }

    int i = 0;

    private async void button1_Click(object sender, EventArgs e)
    {
        // Hang!
        string result = await DoBusyJob();

        this.label1.Text = result;
    }

但是,事实并非如此。它仍然挂起。我意识到我需要在DoBusyJob 中添加额外的await

    public async Task<string> DoBusyJob()
    {
        // Busy Job
        await Thread.Sleep(10000);
        i++;
        return "Finished " + i;
    }

    int i = 0;

    private async void button1_Click(object sender, EventArgs e)
    {
        // OK!
        string result = await DoBusyJob();

        this.label1.Text = result;
    }

我可以知道为什么会这样吗?我真的需要 double await 吗?如果出现以下情况怎么办?

    public async Task<string> DoBusyJob()
    {
        // How to prevent Hang?
        for (int j = 0; j < 10000000; j++) {
            double m = Math.Sqrt(1) + Math.Sqrt(2) + Math.Sqrt(3);
        }
        i++;
        return "Finished " + i;
    }

    int i = 0;

    private async void button1_Click(object sender, EventArgs e)
    {
        // Hang!
        string result = await DoBusyJob();

        this.label1.Text = result;
    }

【问题讨论】:

  • async 关键字不会神奇地使您的 for 循环代码在后台线程上运行。你想做的是await Task.Run( () =&gt; DoExpensiveCpuCalculations());

标签: c# user-interface responsive-design task-parallel-library async-await


【解决方案1】:

关于async 方法,请参阅the excellent answers to this question。

如果您没有将await 与已经异步的方法一起使用,则添加async 不足以使您的方法异步执行。在这种情况下,您需要返回一个代表您的工作执行的Task 实例,例如。致电Task.Factory.StartNew。

【讨论】:

    【解决方案2】:

    async / await FAQ 中有一个很好的答案:

    问。在方法上使用“async”关键字是否会强制对该方法的所有调用都是异步的?

    A.不会。当您调用标记为“异步”的方法时,它会开始在当前线程上同步运行...

    问。 “async”关键字是否会导致方法调用排队到 ThreadPool?创建一个新线程?向火星发射火箭飞船?

    A.不,不,不……

    您可能会发现我的async / await intro 很有帮助。

    【讨论】:

      【解决方案3】:

      我希望在将await 添加到Thread.Sleep(10000); 时我能理解您的// OK!
      无法等待方法 Sleep() 返回 void
      可以仅在将其签名 Task 或 Task&lt;TResult&gt; 指定为返回类型的方法上等待

      异步方法在没有(或直到)await 的情况下同步执行,因此阻塞了 UI 线程
      await Task.Run() 应该立即返回到(上一个)UI 同步上下文,即继续下一个 i++;行执行

      public async Task<string> DoBusyJob()
      {
        // Busy Job
      
        await Task.Run(() =>
          {
              for (int j = 0; j < 10000000; j++)
              {
                  double m = Math.Sqrt(1) + Math.Sqrt(2) + Math.Sqrt(3);
              }
          }
                      );
        i++;
        return "Finished " + i;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-10
        • 1970-01-01
        • 2015-07-24
        相关资源
        最近更新 更多