优雅关闭asp.net核心

App*_*per 6 graceful-degradation asp.net-core

遇到有关正常关闭 asp.net 核心应用程序的非常过时的信息,有人可以填写更新的信息。

用例:我想在应用程序退出时向 consul 注销。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((host, config) =>
        {
        })
        .UseStartup<Service>();
Run Code Online (Sandbox Code Playgroud)

Tao*_*hou 8

要捕获正常关机,您可以尝试IHostApplicationLifetime.

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading;

namespace Microsoft.Extensions.Hosting
{
    /// <summary>
    /// Allows consumers to be notified of application lifetime events. This interface is not intended to be user-replaceable.
    /// </summary>
    public interface IHostApplicationLifetime
    {
        /// <summary>
        /// Triggered when the application host has fully started.
        /// </summary>
        CancellationToken ApplicationStarted { get; }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// Shutdown will block until this event completes.
        /// </summary>
        CancellationToken ApplicationStopping { get; }

        /// <summary>
        /// Triggered when the application host is performing a graceful shutdown.
        /// Shutdown will block until this event completes.
        /// </summary>
        CancellationToken ApplicationStopped { get; }

        /// <summary>
        /// Requests termination of the current application.
        /// </summary>
        void StopApplication();
    }
}
Run Code Online (Sandbox Code Playgroud)

一个演示:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    var life = host.Services.GetRequiredService<IHostApplicationLifetime>();
    life.ApplicationStopped.Register(() => {
        Console.WriteLine("Application is shut down");
    });
    host.Run();
}
Run Code Online (Sandbox Code Playgroud)

  • 你应该在 appLifetime.ApplicationStopping 或 ApplicationStopped 回调中做什么?我不明白这有什么帮助。假设你在控制器中有一个未知的当前正在进行的请求,它可以是 1、10 或 1000,你不知道。你希望它们全部完成。这个方法有什么帮助呢?我希望有某种方式,说“当所有 HttpContext 消失时,意思是,当没有更多请求被处理时,请关闭”? (4认同)
  • @AppDeveloper `IApplicationLifetime` 已过时,而不是 `IHostApplicationLifetime`。你的.net core版本是什么? (2认同)