Search code examples
c#azureazure-worker-rolesazure-cloud-services

HostingEnviornment.QueueBackgroundWorkItem is not working in azure worker role


I am trying to use HostingEnviornment.QueueBackgroundWorkItem on azure worker role for some task execution on background but I am getting exception in the code "operation is not valid due to the current state of the object.".

Can we use HostingEnviornment.QueueBackgroundWorkItem on azure worker role If not then please help me what could I use for process task in background on worker role.


Solution

  • According to 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.

    Per my understanding, HostingEnvironment.QueueBackgroundWorkItem provides you with the ability to enqueue background tasks from within an ASP.Net web application. ASP.NET tracks these tasks and prevents IIS from abruptly terminating the worker process until all background tasks have completed.

    Also, I tried to invoke HostingEnvironment.QueueBackgroundWorkItem within my worker role both on my side and Azure, and a new console application. While invoking this method within a ASP.NET Web application, it could work as expected.

    I assumed that you could leverage Task-based Asynchronous Programming as follows to run your background jobs:

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

    Moreover, you could leverage Hangfire to perform background processing in DotNet. Here are some references, you could refer to them (tutorial and tutorial).