diff --git a/src/Microsoft.Health.TaskManagement/JobHosting.cs b/src/Microsoft.Health.TaskManagement/JobHosting.cs index 2c75adeed2..de96873455 100644 --- a/src/Microsoft.Health.TaskManagement/JobHosting.cs +++ b/src/Microsoft.Health.TaskManagement/JobHosting.cs @@ -111,7 +111,15 @@ public async Task ExecuteAsync(byte queueType, string workerName, CancellationTo try { - await Task.WhenAny(workers.ToArray()); // If any worker crashes exit. + // If any worker crashes or complete after cancellation due to shutdown, + // cancel all workers and wait for completion so they don't crash unnecessarily. + await Task.WhenAny(workers.ToArray()); +#if NET6_0 + cancellationTokenSource.Cancel(); +#else + await cancellationTokenSource.CancelAsync(); +#endif + await Task.WhenAll(workers.ToArray()); } catch (Exception ex) { @@ -176,7 +184,7 @@ private async Task ExecuteJobAsync(JobInfo jobInfo) } catch (OperationCanceledException ex) { - _logger.LogWarning(ex, "Job with id: {JobId} and group id: {GroupId} of type: {JobType} canceled.", jobInfo.Id, jobInfo.GroupId, jobInfo.QueueType); + _logger.LogWarning(ex, "Job with id: {JobId} and group id: {GroupId} of type: {JobType} canceled due to unhandled cancellation exception.", jobInfo.Id, jobInfo.GroupId, jobInfo.QueueType); jobInfo.Status = JobStatus.Cancelled; try