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 i…


This content originally appeared on DEV Community and was authored by Saumya-Ranjan-Mishra

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.");
    }
}
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();

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.


This content originally appeared on DEV Community and was authored by Saumya-Ranjan-Mishra


Print Share Comment Cite Upload Translate Updates
APA

Saumya-Ranjan-Mishra | Sciencx (2025-09-26T08:38:14+00:00) Background Services in ASP.Net core. Retrieved from https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/

MLA
" » Background Services in ASP.Net core." Saumya-Ranjan-Mishra | Sciencx - Friday September 26, 2025, https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/
HARVARD
Saumya-Ranjan-Mishra | Sciencx Friday September 26, 2025 » Background Services in ASP.Net core., viewed ,<https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/>
VANCOUVER
Saumya-Ranjan-Mishra | Sciencx - » Background Services in ASP.Net core. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/
CHICAGO
" » Background Services in ASP.Net core." Saumya-Ranjan-Mishra | Sciencx - Accessed . https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/
IEEE
" » Background Services in ASP.Net core." Saumya-Ranjan-Mishra | Sciencx [Online]. Available: https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/. [Accessed: ]
rf:citation
» Background Services in ASP.Net core | Saumya-Ranjan-Mishra | Sciencx | https://www.scien.cx/2025/09/26/background-services-in-asp-net-core/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.