2

我正在使用 C# 和 .NET Framework 4.5.1 开发一个 ASP.NET MVC Web Api 2 应用程序。

有时,当用户调用 get 时,ApiController我必须在后台运行任务。该任务将用更多数据填充数据库表。

在 Internet 上搜索我发现了这篇文章,如何在 ASP.NET 中运行后台任务。我想使用HangFire。但是阅读它的文档,我还没有找到在我的 ASP.NET Web Api 应用程序上不使用 OWIN 的情况下使用它的方法(我现在没有使用它)。

有没有办法在没有 OWIN 的情况下使用 Hangfire?或者,是否有其他选项可以在 ASP.NET Web Api 2 应用程序上运行后台任务?

4

2 回答 2

5

我不太确定您是否仍然需要这个(我对此表示怀疑),但我会回答这个问题,因为它在 Google 搜索中排名很高。那么,使用OWIN启动Hangfire服务器的常规方法如下......

public void Configuration(IAppBuilder app){
    app.UseHangfireServer();
}

服务器生命周期

但是,根据文档... Hangfire 根本不依赖于 OWIN,您需要做的就是启动和停止BackgroundJobServer

(来源)http://docs.hangfire.io/en/latest/background-processing/processing-background-jobs.html

Hangfire Server 部分负责后台作业处理。服务器不依赖于 ASP.NET,可以在任何地方启动,从控制台应用程序到 Microsoft Azure Worker Role。所有应用程序的单一 API 通过 BackgroundJobServer 类公开

这意味着您将在应用程序启动时启动服务器......

var server = new BackgroundJobServer();

当应用程序结束时你会处理它......

server.Dispose();

而这正是这样app.UseHangfireServer();做的。见源代码...

https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/AppBuilderExtensions.cs#L293

https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.Core/AppBuilderExtensions.cs#L311

请参阅下面使用 global.asax 的示例。

    BackgroundJobServer _server;

    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configuration
            .UseSqlServerStorage("YOUR_CONNECTION_STRING");

        _server = new BackgroundJobServer();
    }

    protected void Application_End(object sender, EventArgs e)
    {
        _server.Dispose();
    }

SQL Server 存储

要注册不需要 OWIN 的 SQL Server 存储,这就是您需要做的一切......

Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage("YOUR_CONNECTION_STRING");

同样,我通过查看这里的源代码得出了这个结论......

https://github.com/HangfireIO/Hangfire/blob/master/src/Hangfire.SqlServer/SqlServerStorageExtensions.cs

结论

Hangfire 不依赖 OWIN,他们已经承认

于 2017-06-23T07:42:29.247 回答
0

您可以使用 ThreadPool.QueueUserWorkItem 来委派您的进程,它将由 CLR 使用线程进行管理。

于 2016-12-24T16:09:44.973 回答