DEV Community

Saumya-Ranjan-Mishra
Saumya-Ranjan-Mishra

Posted on

Background Services in ASP.Net core

What is BackgroundService in .NET?

BackgroundService is an abstract base class in .NET for implementing long-running tasks in the background of your application.

It is part of the Microsoft.Extensions.Hosting namespace and is usually used in ASP.NET Core or Worker Services.

It implements the IHostedService interface, which the .NET generic host uses to manage the lifetime of hosted background tasks.

Key points about BackgroundService:

  1. It provides a ExecuteAsync(CancellationToken stoppingToken) method you override to write your background logic. This runs in a separate thread managed by the host.

  2. The host automatically passes a CancellationToken so you can gracefully stop when the app shuts down.

  3. It starts when your app starts, and stops when the host shuts down.

  4. It is commonly used for Processing messages from a queue (Kafka, RabbitMQ, Azure Service Bus, etc.) or Periodic background tasks (cron-like jobs) or Monitoring external resources or services.

Basic Implementation

Step 1: Create a Background Service
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class MyBackgroundService : BackgroundService
{
    private readonly ILogger<MyBackgroundService> _logger;

    public MyBackgroundService(ILogger<MyBackgroundService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Background Service is starting.");

        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Background Service is doing work at: {time}", DateTimeOffset.Now);

            // Simulate work
            await Task.Delay(5000, stoppingToken);
        }

        _logger.LogInformation("Background Service is stopping.");
    }
}
Enter fullscreen mode Exit fullscreen mode
Step 2: Register it in Program.cs
var builder = WebApplication.CreateBuilder(args);

// Register background service
builder.Services.AddHostedService<MyBackgroundService>();

var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Enter fullscreen mode Exit fullscreen mode

How it works

When the application starts, the host creates and starts the background service.

The ExecuteAsync loop keeps running until the app is shutting down.

When shutdown happens (e.g., Ctrl+C or app stop in cloud), the stoppingToken is triggered → loop ends → cleanup happens gracefully.

But that is not all. This a simple implementation, but in actual production system you might be using the background service for consuming messages from Queue services or using some database and for both of them, we will be using DI for getting the required services.

How to get the dependency services when required without any http request, Follow this link to read about that.

Top comments (0)