How should exceptions be handled inside a BackgroundService's work loop to prevent one failure from silently stopping all future processing?
Short answer
An unhandled exception escaping ExecuteAsync stops the BackgroundService entirely (and depending on configuration, can bring down the whole host), so production code should wrap individual work iterations in try/catch, log the exception, and continue the loop -- reserving…
Advertisement
AModel answer
An unhandled exception escaping ExecuteAsync stops the BackgroundService entirely (and depending on configuration, can bring down the whole host), so production code should wrap individual work iterations in try/catch, log the exception, and continue the loop -- reserving unhandled propagation only for genuinely fatal, unrecoverable conditions that should stop the application.
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
while (!stoppingToken.IsCancellationRequested) {
try {
await ProcessBatchAsync();
} catch (Exception ex) {
_logger.LogError(ex, "Batch processing failed, will retry next cycle");
}
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}Real-world example
A background service silently stopped processing for days after an unhandled exception in one iteration terminated the entire loop; wrapping each iteration in try/catch ensures a single bad item no longer takes down the whole processor.
Likely follow-ups
- What is BackgroundServiceExceptionBehavior and how does it control host-crashing behavior?
- How do you get alerted when a background service has unexpectedly stopped?
Related topics