Fix HostedService to restart loop upon non-cancellation exception (#2144)

This commit is contained in:
Leendert de Borst
2026-06-08 08:57:50 +02:00
committed by Leendert de Borst
parent 5ddb23c9a6
commit 8897476b81
2 changed files with 8 additions and 6 deletions

View File

@@ -58,14 +58,16 @@ public class StatusHostedService<T>(ILogger<StatusHostedService<T>> logger, Glob
// Start the inner while loop with the second cancellationToken.
await ExecuteInnerAsync(stoppingToken);
}
catch (OperationCanceledException ex)
catch (OperationCanceledException ex) when (stoppingToken.IsCancellationRequested)
{
// Expected so we only log information.
// Genuine host shutdown, exit the loop gracefully.
logger.LogInformation(ex, "StatusHostedService<{ServiceType}> is stopping due to a cancellation request.", typeof(T).Name);
break;
}
catch (Exception ex)
{
// Any other exception should not break the loop but instead log the error
// and let the restart logic below retry the worker.
logger.LogError(ex, "An error occurred in StatusHostedService<{ServiceType}>", typeof(T).Name);
}
finally

View File

@@ -65,20 +65,20 @@ public class StatusWorker(ILogger<StatusWorker> logger, Func<IWorkerStatusDbCont
await Task.Delay(5000, stoppingToken);
}
catch (TaskCanceledException)
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
// Expected when the service is stopped - exit the loop gracefully.
// Genuine host shutdown, exit the loop gracefully.
break;
}
catch (Exception e)
{
// Any other exception including database cancellations/timeouts should not break the loop but instead log the error
// and let the restart logic below retry the worker.
logger.LogError(e, "StatusWorker exception");
await Task.Delay(5000, stoppingToken);
}
}
// Service is hard stopping: not in software but on OS level.
// Mark the service as stopped.
try
{
using var dbContext = createDbContext();