Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

Background tasks are being queued and not executed

I've implemented the BackgroundQueue as explained here, and as shown:

public ActionResult SomeAction()
{
    backgroundQueue.QueueBackgroundWorkItem(async ct =>
    {
        //Do some work...
    });

    return Ok();
}

I registered the BackgroundQueue with Autofac as:

builder.RegisterType<BackgroundQueue>()
    .As<IBackgroundQueue>()
    .SingleInstance();

So far so good. I call my controller action and the task is added to the queue. And there it stays without being executed.

So how do I get the task to execute?

Upvotes: 1

Views: 572

Answers (1)

poke
poke

Reputation: 387915

The BackgroundQueue implementation that you took from the documentation is only one part to the solution: The background queue will just keep track of the jobs that you want to be executed.

What you will also need is right below that in the docs: The QueuedHostedService. This is a background service that gets registered with the DI container and is started when the application starts. From then on, it will monitor your BackgroundQueue and work off jobs as they get queued.

A simplified example implementation of this background service, without logging or error handling, could look like this:

public class QueuedHostedService : BackgroundService
{
    private readonly IBackgroundQueue _backgroundQueue;

    public QueuedHostedService(IBackgroundQueue backgroundQueue)
    {
        _backgroundQueue = backgroundQueue;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var workItem = await _backgroundQueue.DequeueAsync(stoppingToken);
            await workItem(stoppingToken);
        }
    }
}

Upvotes: 3

Related Questions