/// <summary> /// Runs a web application and returns a Task that only completes when the token is triggered or shutdown is triggered. /// </summary> /// <param name="host">The <see cref="IWebHost"/> to run.</param> /// <param name="token">The token to trigger shutdown.</param> public static async Task RunAsync(this IWebHost host, CancellationToken token = default) { // Wait for token shutdown if it can be canceled if (token.CanBeCanceled) { await host.RunAsync(token, startupMessage : null); return; } // If token cannot be canceled, attach Ctrl+C and SIGTERM shutdown var done = new ManualResetEventSlim(false); using (var cts = new CancellationTokenSource()) { var shutdownMessage = host.Services.GetRequiredService <WebHostOptions>().SuppressStatusMessages ? string.Empty : "Application is shutting down..."; using (var lifetime = new WebHostLifetime(cts, done, shutdownMessage: shutdownMessage)) { try { await host.RunAsync(cts.Token, "Application started. Press Ctrl+C to shut down."); lifetime.SetExitedGracefully(); } finally { done.Set(); } } } }
/// <summary> /// Returns a Task that completes when shutdown is triggered via the given token, Ctrl+C or SIGTERM. /// </summary> /// <param name="host">The running <see cref="IWebHost"/>.</param> /// <param name="token">The token to trigger shutdown.</param> /// <returns>A <see cref="Task"/> that completes when shutdown is triggered via Ctrl+C or SIGTERM.</returns> public static async Task WaitForShutdownAsync(this IWebHost host, CancellationToken token = default) { var done = new ManualResetEventSlim(false); using (var cts = CancellationTokenSource.CreateLinkedTokenSource(token)) { using (var lifetime = new WebHostLifetime(cts, done, shutdownMessage: string.Empty)) { try { await host.WaitForTokenShutdownAsync(cts.Token); lifetime.SetExitedGracefully(); } finally { done.Set(); } } } }