diff --git a/src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/BackgroundServiceExceptionTests.cs b/src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/BackgroundServiceExceptionTests.cs index 05e30776023592..dfc298e2664c80 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/BackgroundServiceExceptionTests.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/tests/UnitTests/BackgroundServiceExceptionTests.cs @@ -78,8 +78,11 @@ public async Task BackgroundService_AsynchronousException_StopAsync_ThrowsExcept using var host = builder.Build(); await host.StartAsync(); - // Wait for the background service to fail - await Task.Delay(TimeSpan.FromMilliseconds(200)); + // Wait for the host to react to the background service failure + var lifetime = host.Services.GetRequiredService(); + var stoppingTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lifetime.ApplicationStopping.Register(() => stoppingTcs.TrySetResult(null)); + Assert.Equal(stoppingTcs.Task, await Task.WhenAny(stoppingTcs.Task, Task.Delay(TimeSpan.FromSeconds(10)))); await Assert.ThrowsAsync(async () => { @@ -107,8 +110,11 @@ public async Task BackgroundService_AsynchronousException_StopTwiceAsync_ThrowsE using var host = builder.Build(); await host.StartAsync(); - // Wait for the background service to fail - await Task.Delay(TimeSpan.FromMilliseconds(200)); + // Wait for the host to react to the background service failure + var lifetime = host.Services.GetRequiredService(); + var stoppingTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lifetime.ApplicationStopping.Register(() => stoppingTcs.TrySetResult(null)); + Assert.Equal(stoppingTcs.Task, await Task.WhenAny(stoppingTcs.Task, Task.Delay(TimeSpan.FromSeconds(10)))); await Assert.ThrowsAsync(async () => { @@ -222,7 +228,9 @@ public async Task BackgroundService_IgnoreException_StopAsync_DoesNotThrow() using var host = builder.Build(); await host.StartAsync(); - // Wait a bit for the background service to fail + // Wait a bit for the background service to fail. + // This shouldn't cause flakiness: bad order of operations could cause the test to succeed when it should fail, but it shouldn't cause the test to fail when it should succeed. + // Note that waiting for a signal from the service here wouldn't be enough; we also need to wait for the host to process the exception. await Task.Delay(TimeSpan.FromMilliseconds(200)); await host.StopAsync();