是否允许在 ASP.NET 核心控制器中使用 Task.Run?

Is it allowed to use Task.Run in an ASP.NET Core controller?

场景:我有一个带有 "Delete" ASP.NET 核心控制器操作的 Web 服务。实现包括两个步骤:一个便宜的步骤,之后其他操作已经无法再看到已删除的数据,第二个步骤很长 运行 执行实际删除。

是否可以将 Task.Run 用于第二个操作并且从不 await 并且很快将 return 发送给调用者?我知道这个任务可能会因为应用程序关闭而丢失,但它是否允许使用 ASP.NET 核心中的 Task.Run 将工作卸载到后台并且从不等待结果任务?

I know that this task could be lost due to application shutdown, but is it even allowed to offload work to the background using Task.Run in ASP.NET Core and never await the resulting task?

哦,当然,没有什么能阻止这一切。 .NET 和 ASP.NET 允许您使用 Task.Run,响应将立即返回给用户(假设您忽略从 Task.Run 返回的任务)。

Is it okay to use Task.Run for the second operation and never await it and so return to the caller very soon?

你说你知道任务可能会在应用程序关闭时丢失。这是真的;所以第二次删除完全有可能永远不会发生,并且不会有错误或日志消息通知您这一事实。此外,由于任务被忽略,如果该任务失败则不会有通知,因此如果删除代码有问题,没有日志或任何东西会通知您常规失败。如果您对此没问题,那么使用即发即弃就可以了。

在 ASP.NET Core 上,你甚至不需要 Task.Run;您可以只调用执行第二个删除操作的(异步)方法,然后忽略该任务而不是 awaiting 它。

简单地忽略任务将起作用(有或没有 Task.Run),但这确实有负面影响,即 ASP.NET 根本不知道卸载的工作 。所以我会推荐registering the task and having something delay the app shutdown until the tasks have a chance to complete。注册了,还是有可能丢任务的,但是注册可以减少任务丢的几率。