What is a BackgroundService in ASP.NET Core, and how do you register one to run alongside a web application?
Short answer
BackgroundService is an abstract base class for long-running background work that runs within the same process as your web application, started automatically at application startup via AddHostedService () and given a chance to shut down gracefully when the application stops --…
Advertisement
AModel answer
BackgroundService is an abstract base class for long-running background work that runs within the same process as your web application, started automatically at application startup via AddHostedService<T>() and given a chance to shut down gracefully when the application stops -- you implement its ExecuteAsync(CancellationToken) method with your work loop.
public class QueueProcessor : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
await ProcessQueueAsync();
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
builder.Services.AddHostedService<QueueProcessor>();Real-world example
A web API registers a BackgroundService that polls a message queue every few seconds and processes pending notifications, running continuously in the same process without needing a separately deployed worker service.
Likely follow-ups
- How does the host handle exceptions thrown inside ExecuteAsync?
- What's the difference between BackgroundService and a dedicated Worker Service project?
Related topics