为什么建议中间件在 ASP.NET Core 中异步?

Why is it recommended for a middleware to be async in ASP.NET Core?

为什么建议中间件在 ASP.NET Core 中异步?

例如在this教程中建议自定义中间件,我不明白背后的原因。

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public MyMiddleware(RequestDelegate next, ILoggerFactory logFactory)
    {
        _next = next;

        _logger = logFactory.CreateLogger("MyMiddleware");
    }

    public async Task Invoke(HttpContext httpContext)
    {
        _logger.LogInformation("MyMiddleware executing..");

        await _next(httpContext); // calling next middleware

    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyMiddleware>();
    }
} 

根据文档,这是设计使然

The middleware class must include:

  • A public constructor with a parameter of type RequestDelegate.
  • A public method named Invoke or InvokeAsync. This method must:
    • Return a Task.
    • Accept a first parameter of type HttpContext.

参考Write custom ASP.NET Core middleware

我的理解是管道默认设计为异步。

RequestDelegate 是 asp.net 核心管道的核心,需要 Task 才能实现高性能、模块化的 HTTP 请求管道。

public delegate System.Threading.Tasks.Task RequestDelegate(HttpContext context);

来自评论: 感谢@ScottChamberlain

The reason is that with how async was built in to asp.net core it allows for more throughput of web requests for the same hardware when comparing to a non async version.