1

In my MVC app, I have an async method that I need to call but don't want to wait. I don't care about the exception either because my logging framework will catch and log that. I'm doing this now:

_ = auditService.AuditAsync(auditData);

What happens when my main http request is done but my audit service hasn't accepted my audit request (slow network)? I don't want to wait but I want it to finish. Is that possible to have both "fire and forget" and "guaranteed to finish"?

According to this SO post, ASP.NET may throw an exception. Is this still the case in Net Core?

Note: this is not a duplicate of this post and this post. My question is about whether ASP.NET will give me error on my way to call my async method.

Calvin
  • 1,153
  • 2
  • 14
  • 25

1 Answers1

0

In Net Core (tested with 2.0) this seems OK. My sample code:

public async Task<IActionResult> CreateEmail([FromServices] ILogger<EmailsController> logger )
{
    logger.LogInformation("Calling A()...");
    A(logger);
    logger.LogInformation("Done calling A()");
    return Ok(string.Empty);
}

async Task A(ILogger<EmailsController> logger)
{
    logger.LogInformation("A(). entered");
    await Task.Delay(3000);
    logger.LogInformation("A(). working");
    await Task.Delay(3000);
    logger.LogInformation("A(). working");
    await Task.Delay(3000);
    logger.LogInformation("A() done. but ready to throw exception");
    // just to confirm that any exception in this method will be lost if we don't wait
    throw new Exception("Exception from A()");
}

I got 200 status back. No exception from ASP.NET. From log:

log output

So it looks like it's safe to call an async method without waiting, as long as the entire ASP.NET process doesn't crash.

Calvin
  • 1,153
  • 2
  • 14
  • 25