在 .NET Web API 2 的新引导项目中,为您自动创建的大多数端点(例如
AccountController
中的任何内容)都被声明为异步并返回带有 IHttpActionResult
的任务。我对这份声明有几个疑问。
HttpResponseMessage
之间的主要区别是什么?非常感谢任何指点!
3-Is an endpoint declared this way expecting the request to be coming from an async call,
e.g. an AJAX call from a front-end, or does that declaration merely affect how the execution of that
endpoint is handled on the back-end?
正如您所猜测的,这对客户端发送请求的方式没有影响,但会影响后端的执行和请求处理。
2- Are there any major advantages to this declaration over a non-sync implementation?
IE Does this boost performance, scalability, etc...
当然,我们假设您的服务器最多可以同时处理 10 个请求,并且您有一个控制器,该控制器具有保存到数据库的操作,并且保存过程需要 5 秒才能完成,在同步情况下,线程处理您的请求闲置 5 秒等待保存过程完成,这意味着您的服务器无法使用该线程来处理另一个请求,这意味着如果您有 10 个并发请求试图保存到数据库,您的整个服务器将闲置等待这些请求完成,这会导致您的服务器无法处理更多请求,这在网站中非常糟糕。 异步的情况不同,如果您的数据库 ORM 支持异步方法,那么您可以等待该方法完成,从服务器的角度来看,处理您的请求的线程可以被释放来处理另一个请求,这意味着您的服务器可以性能更好,并且要等待您的方法,您需要使用 C# 支持的 async/await。
1- What are the major differences between declaring an endpoint this way versus just returning an HttpResponseMessage?
要回答这个问题,我建议您访问this问题/答案
希望这有帮助。