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
}
}