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:
StartAsync → Runs when the application starts
StopAsync → Runs when the application is shutting down
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();
Join the conversation! Your thoughts help the community grow.