遇到有关 asp.net 核心应用程序正常关闭的非常过时的信息,有人可以填写更新的信息吗?
用例:我想在应用程序退出时向领事取消注册。
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((host, config) =>
{
})
.UseStartup<Service>();
要捕获优雅的关机,您可以尝试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();
}
}
演示:
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();
}