public Task StopAsync(CancellationToken cancellationToken) { if (_stopped) { return(Task.CompletedTask); } _stopped = true; _logger?.Shutdown(); if (!cancellationToken.CanBeCanceled) { cancellationToken = new CancellationTokenSource(_options.ShutdownTimeout).Token; } // Fire IApplicationLifetime.Stopping _applicationLifetime?.StopApplication(); // Fire the IHostedService.Stop _hostedServiceExecutor?.Stop(); // Fire IApplicationLifetime.Stopped _applicationLifetime?.NotifyStopped(); return(Task.CompletedTask); }
public async Task StopAsync(CancellationToken cancellationToken = default) { _stopCalled = true; _logger.Stopping(); using (var cts = new CancellationTokenSource(_options.ShutdownTimeout)) using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken)) { CancellationToken token = linkedCts.Token; // Trigger IHostApplicationLifetime.ApplicationStopping _applicationLifetime.StopApplication(); IList <Exception> exceptions = new List <Exception>(); if (_hostedServices != null) // Started? { foreach (IHostedService hostedService in _hostedServices.Reverse()) { try { await hostedService.StopAsync(token).ConfigureAwait(false); } catch (Exception ex) { exceptions.Add(ex); } } } // Fire IHostApplicationLifetime.Stopped _applicationLifetime.NotifyStopped(); try { await _hostLifetime.StopAsync(token).ConfigureAwait(false); } catch (Exception ex) { exceptions.Add(ex); } if (exceptions.Count > 0) { var ex = new AggregateException("One or more hosted services failed to stop.", exceptions); _logger.StoppedWithException(ex); throw ex; } } _logger.Stopped(); }
public void Dispose() { _logger?.Shutdown(); // Fire IApplicationLifetime.Stopping _applicationLifetime?.StopApplication(); // Fire the IHostedService.Stop _hostedServiceExecutor?.Stop(); (_hostingServiceProvider as IDisposable)?.Dispose(); (_applicationServices as IDisposable)?.Dispose(); // Fire IApplicationLifetime.Stopped _applicationLifetime?.NotifyStopped(); HostingEventSource.Log.HostStop(); }
public async Task StopAsync(CancellationToken cancellationToken = default) { _logger.Stopping(); // Trigger IApplicationLifetime.ApplicationStopping _applicationLifetime?.StopApplication(); IList <Exception> exceptions = new List <Exception>(); if (_hostedServices != null) // Started? { foreach (var hostedService in _hostedServices.Reverse()) { try { await hostedService.StopAsync(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { exceptions.Add(ex); } } } await _hostLifetime.StopAsync(cancellationToken); // Fire IApplicationLifetime.Stopped _applicationLifetime?.NotifyStopped(); if (exceptions.Count > 0) { var ex = new AggregateException("One or more hosted services failed to stop.", exceptions); _logger.StoppedWithException(ex); throw ex; } _logger.Stopped(); }