IHttpActionResult vs async Task

前端 未结 2 1458
执念已碎
执念已碎 2021-02-02 10:03

Most Web API 2.0 methods I\'ve seen return IHttpActionResult, which is defined as an interface that \"defines a command that asynchronously creates a System.Net.Htt

2条回答
  •  离开以前
    2021-02-02 10:14

    Your action may return an IHttpActionResult which performs the action asynchronously when the framework calls its ExecuteAsync.

    But if you must first make some other async calls before creating and returning the result, then you're forced to change the signature to async Task. That's all it is.

    If your controller action code doesn't use await then you can switch back to the simpler signature. However, the result you return will still be asynchronous.

    To be clear, in both cases, you are using asynchronous code.

    The performance benefit is that - provided all calls to the deepest level are async - a web server thread is not blocked during disk or network I/O, your server can handle more requests with fewer resources.

    Think carefully before calling Wait or Result on a Task, or creating a Task yourself within ASP.NET code.

    Two legitimate reasons to hand-code, intentional multi-threading or parallelism for web server code are:

    • when it receives minimal traffic but performs computational work, a call every so often to run a computation over data and you want to use all 16 cores.
    • when making >1 simultaneous calls to database shards or >1 other services, you'd make a task for each shard query up front and await them all.

提交回复
热议问题