【发布时间】:2019-11-28 17:28:31
【问题描述】:
为什么建议中间件在 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>();
}
}
【问题讨论】:
-
不确定您的问题是什么。如果您正在执行同步代码,则不必异步/等待,这也是链接文章所说的。如果您的代码是异步的(并且不需要
awaiting 代码),您只需返回委托 ratehr 而不是等待它,即return _next(httpContext)而不是await _next(httpContext)(然后还从方法声明中删除异步) -
如果你只使用
async/await内部没有真正的异步调用,你就没有必要导致一个状态机(async/await生成一个处理异步代码执行的状态机)。我不知道您在该网站上的何处阅读了“推荐”,它没有在任何地方提及。一直以来的建议是,如果您调用异步代码,请使用async/await,否则不使用并返回任务,除非您需要处理异步委托/方法抛出的异常(try/catch 不适用于return _next(httpContext)
标签: c# asp.net-core .net-core middleware