c# - 多个等待操作或只有一个

标签 c# asp.net-mvc asynchronous async-await

我已经看到了 await 关键字是如何实现的,以及它创建的结果结构。我想我对它有一个初步的了解。然而,是

public async Task DoWork()
{
    await this.Operation1Async();
    await this.Operation2Async();
    await this.Operation3Async();
}

“更好”(一般来说)或

public async Task DoWork()
{
    await this.Operation1Async();
    this.Operation2();
    this.Operation3();
}

第一种方法的问题是它为每个 await 调用创建一个新的 Task?哪个需要一个新线程?

而第一个在第一个 await 上创建一个新的 Task,然后从那里开始的所有内容都在新的 Task 中处理?

编辑 好吧,也许我不太清楚,但是如果我们有

while (await reader.ReadAsync())
{
    //...
}

await reader.NextResultAsync();

// ...

这不是创建了两个任务吗?一个在主线程中使用第一个 ReadAsync,然后在这个新创建的任务中使用 NextResultAsync 的另一个任务。我的问题是真的需要第二个任务,不是吗? 在主线程中创建的一个任务是否足够?所以

while (await reader.ReadAsync())
{
    //...
}

reader.NextResult();

// ...

最佳答案

it is creating a new Task for each await call? Which entails a new thread?

是也不是。是的,它正在为每个异步方法创建一个Taskasync 状态机将创建一个。但是,这些任务不是线程,甚至也不在线程上运行。它们不会“跑”到任何地方。

您可能会发现我的一些博客文章很有用:

  • async intro ,它解释了 async/await 是如何工作的。
  • There Is No Thread ,它解释了任务如何在没有线程的情况下工作。
  • Intro to the Task type ,这解释了一些任务(Delegate Tasks)如何有代码并在线程上运行,但是 async 使用的任务(Promise Tasks)没有。

Whereas the first creates a new Task on the first await and then everything from there is processed in the new Task?

完全没有。任务只完成一次,并且在该任务完成之前,该方法不会继续通过 await。因此,Operation1Async 返回的任务甚至在调用 Operation2 之前就已完成。

关于c# - 多个等待操作或只有一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675526/

相关文章:

c# - 自定义 header 中带有 ID 的 ASP.NET MVC session

c# - true 而不是 True (C#)

c# - ASP.NET MVC 创建一个包含每个用户列表的变量?

c# - 任务一直在等待激活

spring - 在 Spring 中使用 @Async 的 @EventListener

c# - 如何提高大量较小文件的读写速度或性能

c# - 在单个 Web API 请求中使用 MySQL 和 SQL Server 上下文

Scala 和 Play 框架 2.2.0、Action.async 和 isAuthenticated

c# - 将 JSON 对象转换为 Data.Entities.Models.MyModel

c# - 带复选按钮组的工具条