public async Task CancellableStart_CanComplete() { var hostedService = new AsyncFakeHostedService(); var builder = CreateBuilder().ConfigureServices(services => { services.AddSingleton <IHostedService>(hostedService); }); using (var host = builder.Build()) { var startTask = host.StartAsync(); // complete start task hostedService.ContinueStart(); await startTask; Assert.True(hostedService.IsStartCompleted); } }
public async Task CancellableStart_CancelledByCancellationToken() { var hostedService = new AsyncFakeHostedService(); var builder = CreateBuilder().ConfigureServices(services => { services.AddSingleton <IHostedService>(hostedService); }); using (var host = builder.Build()) { var cts = new CancellationTokenSource(); var startTask = host.StartAsync(cts.Token); // cancel token cts.Cancel(); // complete start task hostedService.ContinueStart(); await Assert.ThrowsAsync <OperationCanceledException>(() => startTask); Assert.False(hostedService.IsStartCompleted); } }
public async Task CancellableStart_CancelledByApplicationLifetime() { var hostedService = new AsyncFakeHostedService(); var builder = CreateBuilder().ConfigureServices(services => { services.AddSingleton <IHostedService>(hostedService); }); using (var host = builder.Build()) { var applicationLifetime = host.Services.GetService <IHostApplicationLifetime>(); var startTask = host.StartAsync(); // stop application applicationLifetime.StopApplication(); // complete start task hostedService.ContinueStart(); await Assert.ThrowsAsync <OperationCanceledException>(() => startTask); Assert.False(hostedService.IsStartCompleted); } }