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

☆樱花仙子☆ 提交于 2021-01-27 08:01:54

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/54476221/choosing-not-to-await-async-function-in-action-in-asp-net-core-webapi-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!