c# - 从 Web API Controller 启动长时间运行的操作

标签 c# wcf asp.net-web-api asp.net-web-api2

我正在将现有的自托管 WCF 服务移植到 IIS 托管的 Web API。

服务旨在执行长时间运行的操作,客户端(桌面应用程序)可以启动操作,然后等待结果,或者断开与服务的连接(甚至关闭),稍后再回来获取结果。

目前,WCF 服务有这样的联系(不允许 session ):

public interface IMyServiceContract
{
    // this initiates the action and returns the action id
    int StartAction(ActionParams actionParams);

    // this allows client to query action status (running, completed, faulted)
    ActionStatus GetActionStatus(int actionId);

    // this allows client to download action result, if action was completed
    ActionResult GetActionResult(int actionId);
}

ActionParamsActionResult 是一些数据契约,其中包含输入参数和结果值(无所谓,问题上下文中的内容)。

StartAction 方法创建一个 Action id,通过 Task.Factory.StartNew 启动一个任务,然后返回。客户端定期轮询服务,调用 GetActionStatus 方法,如果完成,客户端使用 GetActionResult 下载结果。

请注意,用户可以启动操作,关闭计算机,运行客户端应用程序, 但稍后他可以下载操作结果。

问题。使用 Web API 做这些事情的方法是什么?

我在 SO 上阅读了一些问题,在 asp.net 上阅读了一些教程,但示例的构建非常相似:它们实现了一个可等待的方法并调用异步 API(例如,来自 EF 6)。据我所知,这不允许“断开连接并稍后下载结果”的场景。

此外,this Stephen Cleary 的帖子告诉我们:

That’s why one of the principles of ASP.NET is to avoid using thread pool threads (except for the request thread that ASP.NET gives you, of course). More to the point, this means that ASP.NET applications should avoid Task.Run.

我错过了什么吗?

最佳答案

我正在使用 Hangfire.io对于长时间运行的任务。 Hangfire 使用数据库并确保执行任务,即使网站(或应用程序池)重新启动也是如此。

它提供了一个非常简单的 API:

BackgroundJob.Enqueue(() => LongRunningTask());

它允许您安排任务以便稍后执行或重复执行任务:

BackgroundJob.Schedule(
    () => LongRunningTask(), 
    TimeSpan.FromDays(7));

RecurringJob.AddOrUpdate(
    () => LongRunningTask(), 
    Cron.Daily);

他们网站上的声明:

Background jobs are being deleted from the storage only on successful execution. Abruptly aborted jobs will be requeued after application restart.
Once a job was created, it will be performed at least once, even if the host process was terminated.

关于c# - 从 Web API Controller 启动长时间运行的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26796012/

相关文章:

c# - WPF 中 RIA 服务的替换

WCF绕过防火墙的两种HTTP通信方式

.net - 使用 NetTcpBinding 中止套接字连接

javascript - 交互式地理 map 的网络技术堆栈?

c# - APPNAME 是经过优化编译的——步进可能会表现得很奇怪;变量可能不可用

c# - 带有泛型的 ASP.NET MVC View /部分

asp.net - 网络API : DelegatingHandler and ApiController on the same thread?

asp.net-web-api2 - 操作参数的必需属性不起作用

c# - MySQL .Net 连接器连接已打开但已关闭

c# - 为 Roslyn SyntaxFactory 指定语言版本