What is the difference between IHostedService and the BackgroundService convenience base class?
Short answer
IHostedService is the low-level interface with just StartAsync and StopAsync methods, giving you full control for services that don't have an inherent continuous loop (like something that just registers/deregisters once at startup and shutdown).
Advertisement
AModel answer
IHostedService is the low-level interface with just StartAsync and StopAsync methods, giving you full control for services that don't have an inherent continuous loop (like something that just registers/deregisters once at startup and shutdown). BackgroundService is a convenience base class implementing IHostedService specifically for the common 'continuous work loop' pattern, handling the StartAsync/StopAsync plumbing so you only write ExecuteAsync.
// Direct IHostedService: no continuous loop needed
public class MetricsRegistrationService : IHostedService {
public Task StartAsync(CancellationToken ct) {
MetricsRegistry.Register("my-service");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken ct) {
MetricsRegistry.Unregister("my-service");
return Task.CompletedTask;
}
}Real-world example
A service that simply registers the application with a service discovery system at startup and deregisters at shutdown implements IHostedService directly, since it has no ongoing loop -- unlike a queue processor, which extends BackgroundService instead.
Likely follow-ups
- Why does BackgroundService exist if IHostedService already covers this case?
- Can a single class implement both patterns for different concerns?
Related topics