.NET › Background Services
What is a BackgroundService in ASP.NET Core, and what does it provide out of the box?
BeginnerAnswer
BackgroundService is an abstract base class implementing IHostedService, designed for long-running background work that runs alongside the main application (like an ASP.NET Core web app or worker service). You override its ExecuteAsync(CancellationToken) method with your work loop, and the host manages starting it at application startup and gracefully signaling cancellation at shutdown.
public class EmailQueueProcessor : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
await ProcessQueueAsync();
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
// Registration
builder.Services.AddHostedService<EmailQueueProcessor>();Real-world example A web API registers a BackgroundService that polls a message queue every few seconds and processes pending email notifications, running continuously in the same process as the API without needing a separate deployed service.