【问题标题】:Understanding the difference between the following async-await calls了解以下 async-await 调用之间的区别
【发布时间】:2018-02-21 11:10:22
【问题描述】:

这些调用的行为是否相似?它们的行为是否与 async-await 的运行方式相同 - 可以或不能在相同的原始线程上下文上运行?还是第一个确保执行发生在不同的线程上下文中?

第一种方式-

Task task = SomeAsyncTask();
await task();

第二种方式——

await SomeAsyncTask();

【问题讨论】:

    标签: c# async-await threadpool


    【解决方案1】:

    如果Task task = SomeAsyncTask();await task(); 之间有代码,您的任务将开始执行异步代码,并且您当前的线程将同时执行该代码。

    否则,它们相等..

    Task task = SomeAsyncTask();
    //Codes executed on current thread while SomeAsyncTask is running
    await task();
    

    【讨论】:

      【解决方案2】:

      All asynchronous methods start synchronously.

      即:

      await SomeAsyncTask();
      

      完全一样:

      var task = SomeAsyncTask();
      await task;
      

      在这两种情况下,SomeAsyncTask 将一直运行,直到它完成或遇到异步 await,此时它会返回一个任务。然后该任务由调用方法awaited。

      【讨论】:

        猜你喜欢
        • 2020-09-16
        • 2016-02-26
        • 2016-07-11
        • 2020-03-25
        • 1970-01-01
        • 2012-05-04
        • 2020-08-20
        • 2021-09-20
        • 2015-01-06
        相关资源
        最近更新 更多