gpt4 book ai didi

c# - HostingEnviornment.QueueBackgroundWorkItem 无法在 azure 辅助角色中工作

转载 作者:行者123 更新时间:2023-11-30 14:24:12 25 4
gpt4 key购买 nike

我尝试在 azure 辅助角色上使用 HostingEnviornment.QueueBackgroundWorkItem 在后台执行某些任务,但我在代码中遇到异常“由于当前状态,操作无效对象。”.

我们可以在 azure 辅助角色上使用 HostingEnviornment.QueueBackgroundWorkItem 如果没有,请帮助我在辅助角色的后台处理任务时可以使用什么。

最佳答案

根据System.Web.Hosting.HostingEnvironmentQueueBackgroundWorkItem :

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 Web 应用程序中对后台任务进行排队。 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在 DotNet 中执行后台处理。这里有一些引用资料,您可以引用它们( tutorialtutorial )。

关于c# - HostingEnviornment.QueueBackgroundWorkItem 无法在 azure 辅助角色中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com