Question

So I've been working with background processing and event-driven systems, namely Azure WebJobs and ServiceBus. And while there is extensive use of async/await programming, I'm always wondering if it is generally bad practice to await asynchronous operations when not at all needing the results further in the program. More like a fire and forget.

I know that await won't block a thread but why even force the CPU to return to your method after the await if nothing happens or you don't need the method's result. Why wouldn't one just skip the await on your operation, the CPU never needs to return to your method and the thread can be returned to the pool. This situation is a fire-and-forget one.

EDIT: Code examples

async Task WriteEvent(string event)
{
    //some logic
    Event parsedEvent = new Event(event);
    //other logic

    _eventService.WriteEventAsync(parsedEvent); // no await
}

The alternative to the above code block:

async Task WriteEvent(string event)
{
    //some logic
    Event parsedEvent = new Event(event);
    //other logic

    await _eventService.WriteEventAsync(parsedEvent); // await
}
Was it helpful?

Solution

There is nothing wrong with fire-and-forget asynchronous operation. But you need to make sure you can handle possible exceptions, as there is no one to handle them in such situation.

One possible solution is :

async void WriteEventAsyncEx()
{
    try
    {
        await _eventService.WriteEventAsync(parsedEvent);
    }
    catch(Exception ex)
    {
        // handle exception
        // letting it through would result in UnhandledTaskException killing application
    }
}

async Task WriteEvent(string event)
{
    //some logic
    Event parsedEvent = new Event(event);
    //other logic

    WriteEventAsyncEx(); // no await
}
Licensed under: CC-BY-SA with attribution
scroll top