控制器动作中的长时间运行方法-MVC [英] Long running method in controller action - MVC
问题描述
我在 WebAPI-MVC
public IActionResult Post(Model model)
{
ALongRunningMethod();
return Ok();
}
我有两个选择.
- 等待该方法完成.但是,如果时间太长怎么办?API不会超时吗?
- 使用
Tasks
在单独的线程中运行该代码,但立即返回Ok(200 HTTP代码)
?如果在该长时间运行的方法中发生某些异常怎么办?
- Wait for the method to complete. But, what if its too long ? Doesn't the API timeout ?
- Run that in a separate thread using
Tasks
but returnOk (200 HTTP Code) immediately
? What if some exception occur in that long running method ?
完全困惑.在这种情况下我该怎么办?
Totally confused. What should I do in this case ?
推荐答案
这是Web应用程序中的常见问题.我将创建一个 GUID
,将其传递到任务中,运行该任务,然后传递回 GUID
.同时,任务将继续.如果您有数据库,则可以将 GUID
从任务保存到DB,指示某些状态.例如您可能有一个名为'Task'的数据库表,其中有 TaskID
和 Status
列.
This is a common issue in web applications. I would create a GUID
, pass it into a task, run the task, pass back the GUID
. In the mean time, the task will continue. If you have a database you could save the GUID
to the DB from the task, indicating some status. e.g. You could have a database table called 'Task' with columns TaskID
and Status
.
然后,您可以使用 GUID
定期检索(轮询)任务状态.
Then you can use the GUID
to retrieve (poll) for the status of the task at regular intervals.
注释者的正确说法是,ASP.NET中长时间运行的任务是危险的游戏,因为您无法控制应用程序域的生存期.
The commenter is correct in saying that long-running tasks in ASP.NET is a dangerous game because you have no control over the lifetime of the app domain.
这篇关于控制器动作中的长时间运行方法-MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!