Web Api – Fire and Forget

And I need to “fire and forget”

I have a blog post that goes into details of several different approaches for fire-and-forget on ASP.NET.

In summary: first, try not to do fire-and-forget at all. It’s almost always a bad idea. Do you really want to “forget”? As in, not care whether it completes successfully or not? Ignore any errors? Accept occasional “lost work” without any log notifications? Almost always, the answer is no, fire-and-forget is not the appropriate approach.

A reliable solution is to build a proper distributed architecture. That is, construct a message that represents the work to be done and queue that message to a reliable queue (e.g., Azure Queue, MSMQ, etc). Then have an independent backend that process that queue (e.g., Azure WebJob, Win32 service, etc).

Should I just call Task.Run() without any async-await?

No. This is the worst possible solution. If you must do fire-and-forget, and you’re not willing to build a distributed architecture, then consider Hangfire. If that doesn’t work for you, then at the very least you should register your cowboy background work with the ASP.NET runtime via HostingEnvironment.QueueBackgroundWorkItem or my ASP.NET Background Tasks library. Note that QBWI and AspNetBackgroundTasks are both unreliable solutions; they just minimize the chance that you’ll lose work, not prevent it.

Leave a Comment