K Singh
K Singh

Reputation: 1

Create Multiple Instance of BackgroundService in ASP.NET Core

I am new to this and would appreciate some pointers or examples.

How can I create multiple instances of a BackgroundService in an ASP.NET Core app that process messages from a queue? Should I use BackgroundService or IHostedService ?

Thanks

Upvotes: 0

Views: 475

Answers (2)

Jalpa Panchal
Jalpa Panchal

Reputation: 12799

IHostedService is an interface that defines two methods: StartAsync(CancellationToken) and StopAsync(CancellationToken). You need to implement the logic for starting and stopping the service.

BackgroundService is an abstract class that implements IHostedService and provides a template method pattern via the ExecuteAsync(CancellationToken) method. You only need to override this method to execute the background task. It handles the starting and stopping processes for you, making it simpler to use for background tasks.

You could use BackgroundService which is a bit more convenient since it's a base class that simplifies some of the implementation details.

BackgroundService:

public class QueueProcessor : BackgroundService
{
    private readonly MessageQueue _queue;

    public QueueProcessor(MessageQueue queue)
    {
        _queue = queue;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var message = await _queue.DequeueAsync(stoppingToken);

            if (message != null)
            {
                ProcessMessage(message);
            }
        }
    }

    private void ProcessMessage(string message)
    {
        Console.WriteLine($"Processing: {message}");
    }
}



public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<MessageQueue>();  
    services.AddHostedService<QueueProcessor>();
}

To run multiple instances of the QueueProcessor, you would normally add multiple services. With BackgroundService, you can also run multiple

Upvotes: 0

sommmen
sommmen

Reputation: 7658

You can use either since BackGroundService is just an implementation of IHostedService.

Usually you'd want to stick with your implementation of BackgroundService

BackgroundService is a base class for implementing a long running IHostedService.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio

Upvotes: 0

Related Questions