Example #1
0
    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();
                }
            }
        }
    }
Example #2
0
    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();
                }
            }
        }
    }