问题描述
这是我的问题:我需要在 ApiController 中调用多个第 3 方方法.这些方法的签名是Task DoSomethingAsync(SomeClass someData, SomeOtherClass moreData)
.我希望这些调用在 ApiController 将数据发送回客户端后继续在后台运行.当 DoSomethingAsync
完成时,我想做一些日志记录并可能将一些数据保存到文件系统.我怎样才能做到这一点?我更喜欢使用 asyny/await 语法.
Here's my problem: I need to call multiple 3rd party methods inside an ApiController. The signature for those methods is Task DoSomethingAsync(SomeClass someData, SomeOtherClass moreData)
. I want those calls to continue running in the background, after the ApiController has sent the data back to the client. When DoSomethingAsync
completes I want to do some logging and maybe save some data to the file system. How can I do that? I'd prefer to use the asyny/await syntax.
推荐答案
Stephen 描述了为什么在 ApiController 中启动长时间运行的即发即弃任务是一个坏主意.
Stephen described why starting essentially long running fire-and-forget tasks inside an ApiController is a bad idea.
也许您应该创建一个单独的服务来执行那些即发即忘的任务.该服务可以是一个不同的 ApiController,一个队列背后的工作者,任何可以独立托管并具有独立生命周期的东西.
Perhaps you should create a separate service to execute those fire-and-forget tasks. That service could be a different ApiController, a worker behind a queue, anything that can be hosted on its own and have an independent lifetime.
这将使管理不同任务生命周期变得更加容易,并将长期运行任务的关注点与 ApiController 的核心职责分开.
This would make management of the different task lifetimes much easier and separate the concerns of the long-running tasks from the ApiController's core responsibilities.
这篇关于WebAPI 中的长时间运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!