选择不等待ASP.NET Core WebAPI控制器中正在运行的异步功能 [英] Choosing not to await async function in action in ASP.NET Core WebAPI controller

查看:277
本文介绍了选择不等待ASP.NET Core WebAPI控制器中正在运行的异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况如下:

  • 后端:Asp.NET Core WebAPI 2.2
  • 前端:使用API​​的iOS和Android

我具有允许用户向其他用户发送消息的功能.发送消息是通过异步操作完成的:

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

公共异步任务< IActionResult>CreateMessage

此操作按顺序执行以下操作:

This action does the following in order:

  1. 验证
  2. 等待消息持久存储到数据库
  3. 等待通过SignalR通知相关客户
  4. 不等待通过Azure Notification Hub发送推送通知.
  5. 返回200 OK.
  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是异步的,但我选择不等待它,以避免等待请求完成而导致的UI锁定.目前,所有这些似乎都可以正常工作.

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?

致谢

推荐答案

  • 任何异常都将被静默忽略.
  • 应用程序无法检测到操作何时完成.这意味着,比该代码高"的所有内容都不知道您的代码仍在做某事.ASP.NET,IIS和您的负载均衡器不知道您的应用程序仍在进行中.其中一些管理系统可以(并且将)关闭您的应用程序.例如,IIS执行定期的AppPool回收.
    • 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.

    ASP.NET上Fire和Forget的用例比大多数人想象的要少得多.不仅您必须对无声吞咽的错误感到满意,而且还必须对偶尔丢失该工作感到满意.

    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.

    我选择不等待它,以避免因等待请求完成而导致UI锁定.

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

    这听起来像一个UI问题,应该通过UI解决方案来解决.

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

    这篇关于选择不等待ASP.NET Core WebAPI控制器中正在运行的异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆