Background Services and Hosted Services in ASP.NET Core

What are Background Services and Hosted Services?

In ASP.NET Core, background services run tasks outside the scope of a user's request. These are useful for scenarios like data processing, sending notifications, or periodic cleanup tasks.

  • Background Services: Long-running tasks that run in parallel with the main application.
  • Hosted Services: Services that implement the IHostedService interface for managing background tasks.
  • Built-In Support: ASP.NET Core provides BackgroundService, a base class to simplify creating hosted services.

Creating Background Services in ASP.NET Core

Follow these steps to create and use a background service:

1. Create a Background Service


// Services/ExampleBackgroundService.cs
using Microsoft.Extensions.Hosting;

public class ExampleBackgroundService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine("Background service is running...");
            await Task.Delay(5000, stoppingToken); // Simulate periodic work
        }
    }
}

                

The ExecuteAsync method runs continuously, performing work at regular intervals.

2. Register the Background Service


// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add the background service to the dependency injection container
builder.Services.AddHostedService<ExampleBackgroundService>();

var app = builder.Build();

app.MapGet("/", () => "Welcome to Background Services Demo!");

app.Run();

                

Use the AddHostedService method to register the service.

3. Run the Application

When you run the application, the background service starts running alongside the web server. Observe the console output:


Background service is running...
Background service is running...

                

The message appears every 5 seconds as the service executes.


Creating a Custom Hosted Service

1. Implement the IHostedService Interface


// Services/CustomHostedService.cs
using Microsoft.Extensions.Hosting;

public class CustomHostedService : IHostedService
{
    private Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("Hosted service starting...");
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        Console.WriteLine("Hosted service task running...");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        Console.WriteLine("Hosted service stopping...");
        _timer?.Dispose();
        return Task.CompletedTask;
    }
}

                

The StartAsync method initializes the service, while StopAsync cleans up resources.

2. Register the Hosted Service


// Program.cs
builder.Services.AddHostedService<CustomHostedService>();

                

Add the hosted service to the dependency injection container.


Key Benefits of Background Services

  • Asynchronous Processing: Offload work from the main request-response cycle.
  • Periodic Tasks: Perform tasks at scheduled intervals.
  • Scalability: Handle heavy workloads without blocking the application.