控制器动作中的长时间运行方法-MVC [英] Long running method in controller action - MVC

查看:64
本文介绍了控制器动作中的长时间运行方法-MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WebAPI-MVC

public IActionResult Post(Model model)
{
      ALongRunningMethod();
      return Ok();
}

我有两个选择.

  1. 等待该方法完成.但是,如果时间太长怎么办?API不会超时吗?
  2. 使用 Tasks 在单独的线程中运行该代码,但立即返回 Ok(200 HTTP代码)?如果在该长时间运行的方法中发生某些异常怎么办?
  1. Wait for the method to complete. But, what if its too long ? Doesn't the API timeout ?
  2. Run that in a separate thread using Tasks but return Ok (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屋!

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