ApplicationStarted:
应用程序完全启动后触发。
ApplicationStopping
:应用程序即将停止时触发。ApplicationStopped
:应用程序完全停止后触发。
我们创建一个简单的ASP.NET Core 应用,使用如下代码:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var lifetime = app.Services.GetService<IHostApplicationLifetime>();
lifetime.ApplicationStarted.Register(() => Console.WriteLine("===== Server is starting"));
lifetime.ApplicationStopping.Register(() =>Console.WriteLine("===== Server is stopping"));
lifetime.ApplicationStopped.Register(() => Console.WriteLine("===== Server has stopped"));
app.Run(async context =>
{
await context.Response.WriteAsync("Hello world");
});
app.Run();
我们运行应用程序:
我们可以看到ApplicationStarted事件被触发。我们使用Ctrl+C关闭应用程序。
可以看到ApplicationStopping和ApplicationStopped事件被触发。
源代码地址:
https://github.com/bingbing-gui/AspNetCore-Skill/tree/master/src/aspnetcore-knowledge-point/application-lifetime