Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

Proper Exception Handling and Graceful Shutdown in BackgroundService and IHostedService [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Rozpustnik: 57
Data dołączenia: Mar 2019
Posty: 18
Dzięki: 40
1 miesięcy temu · Jul 2, 2026 10:07 PM
#1

Why unhandled exceptions inside BackgroundService.ExecuteAsync crash the entire .NET application by default:

In .NET 6+, HostOptions.BackgroundServiceExceptionBehavior defaults to StopHost, shutting down your API server if a background timer throws an unhandled exception.

Robust Background Service Pattern:

CSHARP
public class IngestionWorker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await ProcessWorkQueueAsync(stoppingToken);
            }
            catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
            {
                // Normal graceful shutdown, exit loop
                break;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing background batch. Retrying in 5s...");
                await Task.Delay(5000, stoppingToken);
            }
        }
    }
}
channel_concurrency
Reactive & Pipeline
MEMBER
Rozpustnik: 156
Data dołączenia: Jan 2022
Posty: 10
Dzięki: 16
1 miesięcy temu · Jul 3, 2026 2:00 AM
#2

Catching OperationCanceledException when stoppingToken.IsCancellationRequested is true ensures clean host shutdown without polluting error logs.

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · Jul 3, 2026 11:11 AM
#3

Critical template for writing reliable background worker services.