英文:
Non awaited async method in middleware - does this work and is this a valid pattern?
问题
I've come across this code in one of our applications (ASP.NET MVC .NET 7 c#). This code is injected into the middleware pipeline.
Audit()
方法是一个异步方法,但没有等待它,可能是为了速度考虑,也许假设该调用不会导致管道延迟。开发者只是简单地添加了 "fire and forget" 注释。
Questions:
-
.Audit
调用是否保证完成?如果是,通过哪个上下文运行此方法以完成? -
在这个管道中以这种方式等待异步方法是否是有效的优化?这是否导致更快的管道?
-
这是否是可接受和有效的模式?
public class LoggingMiddleware : IMiddleware
{
private readonly IAuditService _auditService;
public LoggingMiddleware(IAuditService auditService)
{
_auditService = auditService;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await next.Invoke(context);
_ = _auditService.Audit(context); // fire and forget
}
}
英文:
I've come across this code in one of our applications (ASP.NET MVC .NET 7 c#). This code is injected into the middleware pipeline.
The Audit()
method is an async method but it's not awaited, presumably for speed reasons, perhaps assuming that the call will not cause any delay in the pipeline. The dev has simply commented "fire and forget".
Questions:
-
Is the
.Audit
call guaranteed to complete? If so, which context is running this method through to completion? -
Is awaiting an async method in this pipeline in this way is a valid optimisation? Does this result in a faster pipeline?
-
Is this an acceptable and valid pattern?
public class LoggingMiddleware : IMiddleware
{
private readonly IAuditService _auditService;
public LoggingMiddleware(IAuditService auditService)
{
_auditService = auditService;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await next.Invoke(context);
_ = _auditService.Audit(context); // fire and forget
}
}
答案1
得分: 2
Sure, here are the translated parts:
Is the .Audit call guaranteed to complete? If so, which context is running this method through to completion?
没有,它不能保证任务完成。它将任务放入“TaskScheduler”以便完成。如果应用程序崩溃,数据将丢失。无论如何,似乎需要额外的“Task.Run”。
Is awaiting an async method in this pipeline in this way is a valid optimisation? Does this result in a faster pipeline?
很可能await
会减慢管道的速度。
Is this an acceptable and valid pattern?
这取决于数据一致性的要求。
英文:
> Is the .Audit call guaranteed to complete? If so, which context is running this method through to completion?
No, it does not guarantee task completion. It puts task to TaskScheduler
for completion. If application crashes data will be lost. Anyway looks like additional Task.Run
is needed here.
> Is awaiting an async method in this pipeline in this way is a valid optimisation? Does this result in a faster pipeline?
Most likely await
will slowdown pipeline.
> Is this an acceptable and valid pattern?
It depends on requirements of data consistency.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论