Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choosing not to await async function in action in ASP.NET Core WebAPI controller

The scenario is the following:

  • Backend: Asp.NET Core WebAPI 2.2
  • Frontend: iOS and Android which consumes the API

I have a function allowing the user to send messages to other users. The sending of a message is done in an asynchronous action:

public async Task<IActionResult> CreateMessage

This action does the following in order:

  1. Validation
  2. Awaits persistance of the message to DB
  3. Awaits the notification of relevant clients via SignalR
  4. Doesn't await the sending of push notification via Azure Notification Hub.
  5. Returns a 200 OK.

The last two lines in the action is the following:

_notificationHubProxy.SendNotification(messageToReturnResource.SenderName, messageToPush, recipientId);

return Ok(messageToReturnResource);

SendNotification is asynchronous but I choose to not await it to avoid UI-locks caused by the waiting of the request to finish. At the moment all this seems to work fine.

My question is really the following: is this okey (i.e. to not await), or is this an example of writing bad code which will cause problems when I have many clients using the application?

Regards

like image 815
solojuve1897 Avatar asked Jan 27 '23 19:01

solojuve1897


1 Answers

There are a few problems with fire-and-forget on ASP.NET (both Core and Classic):

  • Any exceptions will be silently ignored.
  • The application cannot detect when the operation has completed. This means that everything "higher" than this code has no idea that your code is still doing something; ASP.NET, IIS, and your load balancer have no idea that your application still has something in progress. Some of these are management systems that can (and will) shut down your app. E.g., IIS performs regular AppPool recycling.

The use cases for Fire and Forget on ASP.NET are much rarer than most people think. Not only do you have to be OK with silently swallowing errors, but you also have to be OK with occasionally losing that work.

I choose to not await it to avoid UI-locks caused by the waiting of the request to finish.

That sounds like a UI problem that should be solved by a UI solution.

like image 147
Stephen Cleary Avatar answered Feb 08 '23 17:02

Stephen Cleary