Introduction
In modern ASP.NET Core applications, not all tasks need to run as part of a user request. Some operations, such as sending emails, processing queues, cleaning up data, or running scheduled jobs, are better handled in the background.
This is where Background Services in ASP.NET Core come into play.
Using IHostedService, developers can run background tasks efficiently without blocking the main application thread. This is especially useful in Web APIs, microservices, and cloud-based applications.
In this article, you will learn how to implement background services in ASP.NET Core using IHostedService step by step, with practical examples and best practices.
What is IHostedService in ASP.NET Core?
Understanding IHostedService in Simple Words
IHostedService is an interface in ASP.NET Core that allows you to run background tasks when your application starts and stops.
It provides two main methods:
This makes it ideal for long-running or recurring background operations.
Why Use Background Services?
Run tasks without blocking user requests
Improve performance of Web APIs
Handle long-running operations
Process background jobs or queues
Schedule recurring tasks
Step 1: Create an ASP.NET Core Web API Project
You can create a new project using the .NET CLI:
dotnet new webapi -n BackgroundServiceDemo
cd BackgroundServiceDemo
Step 2: Create a Background Service Class
Implement IHostedService
using Microsoft.Extensions.Hosting;
public class MyBackgroundService : IHostedService
{
private Timer _timer;
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
Console.WriteLine($"Background task running at: {DateTime.Now}");
}
public Task StopAsync(CancellationToken cancellationToken)
{
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
}
This service runs every 5 seconds in the background.
Step 3: Register the Background Service
Open Program.cs and register the service:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Register Background Service
builder.Services.AddHostedService<MyBackgroundService>();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
Now, the background service starts automatically when the application runs.
Step 4: Understanding the Flow
How It Works
This ensures clean startup and shutdown behavior.
Step 5: Using BackgroundService Class (Recommended)
Instead of implementing IHostedService manually, ASP.NET Core provides a BackgroundService base class.
Example Using BackgroundService
using Microsoft.Extensions.Hosting;
public class WorkerService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"Worker running at: {DateTime.Now}");
await Task.Delay(5000, stoppingToken);
}
}
}
Register It
builder.Services.AddHostedService<WorkerService>();
This approach is cleaner and easier to maintain.
Step 6: Real-World Use Cases
Common Use Cases
Sending emails in background
Processing message queues
Generating reports
Cleaning old data
Syncing data between services
Step 7: Handling Dependencies
You can inject services into background services.
Example
public class WorkerService : BackgroundService
{
private readonly ILogger<WorkerService> _logger;
public WorkerService(ILogger<WorkerService> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Background task running...");
await Task.Delay(5000, stoppingToken);
}
}
}
This allows better logging and integration with ASP.NET Core services.
Step 8: Error Handling and Cancellation
Best Practices
Example:
try
{
await Task.Delay(5000, stoppingToken);
}
catch (TaskCanceledException)
{
// Handle cancellation
}
Step 9: Best Practices for Background Services
Follow These Best Practices
Use BackgroundService instead of raw IHostedService
Keep tasks lightweight
Avoid long blocking operations
Use logging for monitoring
Use dependency injection
Step 10: Advanced Scenario (Queue Processing)
In real applications, background services often process queues.
Example:
This improves performance and scalability.
Summary
IHostedService in ASP.NET Core allows developers to run background tasks efficiently without affecting user requests. By using BackgroundService, dependency injection, and proper error handling, you can build scalable and reliable applications. Background services are widely used in Web APIs, microservices, and cloud environments to handle tasks like email sending, queue processing, and scheduled jobs.