HostingEnviornment.QueueBackgroundWorkItem 未在 azure worker 角色中工作

HostingEnviornment.QueueBackgroundWorkItem is not working in azure worker role

我正在尝试在 azure worker 角色上使用 HostingEnviornment.QueueBackgroundWorkItem 在后台执行某些任务,但我在代码 "operation is not valid due to the current state of the object.".

我们可以在 azure worker 角色上使用 HostingEnviornment.QueueBackgroundWorkItem 如果不能,请帮助我在 worker 角色的后台处理任务中可以使用什么。

根据System.Web.Hosting.HostingEnvironment and QueueBackgroundWorkItem

Differs from a normal ThreadPool work item in that ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing. This API cannot be called outside of an ASP.NET-managed AppDomain. The provided CancellationToken will be signaled when the application is shutting down.

根据我的理解,HostingEnvironment.QueueBackgroundWorkItem 使您能够从 ASP.Net 网络应用程序中对后台任务进行排队。 ASP.NET 跟踪这些任务并防止 IIS 在所有后台任务完成之前突然终止工作进程。

此外,我尝试在我这边和 Azure 的工作者角色中调用 HostingEnvironment.QueueBackgroundWorkItem,以及一个新的控制台应用程序。在 ASP.NET Web 应用程序中调用此方法时,它可以按预期工作。

我假设您可以按如下方式利用 Task-based Asynchronous Programming 来 运行 您的后台作业:

var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;

Task.Factory.StartNew((token) => {
    var ct = (CancellationToken)token;
    while (!ct.IsCancellationRequested)
    {
        //do your job
    }
}, cancellationToken, cancellationToken);

此外,您可以利用 Hangfire to perform background processing in DotNet. Here are some references, you could refer to them (tutorial and tutorial).