gpt4 book ai didi

c# - 这个 MVC4 API 调用应该是异步的吗?

转载 作者:太空狗 更新时间:2023-10-30 00:40:49 25 4
gpt4 key购买 nike

我刚刚继承了一个 MVC4 API 应用程序,它充当一些其他服务的基本请求转发器。该应用程序的基本结构如下所示:

[请求] -> [rest api] -> [本地处理] -> [同步调用外部服务] -> [响应的本地处理] -> [响应]

本地处理主要是验证内容并将其保存到数据库中。一点都不重。在极端情况下,外部请求可能需要 1 - 200 秒以上的时间。 API 通常每小时处理数千个请求。

该应用程序托管在一个小型的 Azure 云实例上。

我感到困惑的是线程。从 API 处理程序方法到对外部服务的外部调用的整个过程都设置为异步的:

public async Task<CustomResponseType> Post([FromBody] inputType) {
// some validation
...
// save some stuff to a db
...

var response = await httpClient.PostAsync(someRequest)
return await response.Content.ReadAsStringAsync();
}

那么首先,让这个过程异步有什么好处?据我了解,IIS 应该为传入请求管理自己的线程池,并且由于我们正在等待对单个外部服务调用的同步响应,因此看起来并没有实际并行处理任何事情。乍一看,异步服务请求似乎会竞争 IIS 将使用的相同资源,而且实际上同步执行所有请求可能更有效。

我读过这个:http://msdn.microsoft.com/en-us/library/ee728598%28v=vs.98%29.aspx?wa=wsignin1.0并了解 IIS 端可能存在称为“线程饥饿”的东西。那篇文章支持异步在这种情况下可能有帮助的想法,但我很难理解为什么。只增加 IIS 线程的数量会更容易吗?他们不会都在争夺同样的资源吗? IIS线程使用起来更重的问题吗?

最佳答案

async/await的使用并不意味着“生成新线程来进行这些异步调用”。

Eric Lippert 描述了使用 async/await 的过程在他认真的时候很漂亮Asynchronous Programming in C# 5 :

The “async” modifier on the method does not mean “this method is automatically scheduled to run on a worker thread asynchronously”. It means the opposite of that; it means “this method contains control flow that involves awaiting asynchronous operations and will therefore be rewritten by the compiler into continuation passing style to ensure that the asynchronous operations can resume this method at the right spot.” The whole point of async methods it that you stay on the current thread as much as possible. They’re like coroutines: async methods bring single-threaded cooperative multitasking to C#.

当您使用 async方法上的修饰符,编译器将其推断为一个符号,并根据您的方法流程和 await 的使用生成状态机里面的关键字。它使用额外的ThreadPool线程,相反,当你await在 I/O 绑定(bind)异步方法上,编译器将控制权交还给调用者,在 ASP.NET 的情况下,这将使当前线程返回到 ASP.NET 线程池以用于其他传入的请求。一旦我/O 工作已完成,继续将通过同样由 ThreadPool 分配的 IOCP 线程调用,这意味着您实际上是在让线程做更多事情,而根本不创建新线程。

有很多很棒的帖子描述了这种效果:

  1. There Is No Thread - By Stephan Cleary
  2. Does async and await increase performance of an ASP.Net application
  3. ASP.NET async/await part 2
  4. The Magic of using Asynchronous Methods in ASP.NET 4.5 plus an important gotcha (By Scott Hanselman)
  5. Why use async requests instead of using a larger threadpool?

关于c# - 这个 MVC4 API 调用应该是异步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24366354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com