ASP.NET Core 知识速递:IHostApplicationLifetime 接口

ASP.NET Core 知识速递:IHostApplicationLifetime 接口

编程文章jaq1232025-03-19 14:22:5525A+A-
1. IHostApplicationLifetime 对象
这一节我们来了解一下IHostApplicationLifetime 这个接口,来看官方定义:
IHostApplicationLifetime接口允许用户接收应用程序生命周期事件的通知。该接口并非为用户设计用来替换或重写的,其主要作用是将应用程序生命周期的变化通知用户。换句话说,这个接口仅用于通知功能,用户无需实现或重写它

IHostApplicationLifetime 提供了三个核心事件,用于处理应用程序生命周期的关键时刻:

ApplicationStarted方法在应用程序完全启动(所有服务已配置完成)后触发,通常用于执行应用程序启动后的自定义逻辑。

ApplicationStopping方法在应用程序即将停止时触发。此阶段通常仍可进行一些清理操作,比如释放资源或保存数据。

ApplicationStopped方法在应用程序完全停止后触发。此阶段应只执行简单的终止逻辑,因为此时应用程序的其他部分可能已经被释放。

2. 例子


await Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService(); }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); }).Build() .RunAsync();
public class SampleHostedService : IHostedService{ IHostApplicationLifetime _lifetime; ILogger _log;
public SampleHostedService(IHostApplicationLifetime lifetime, ILogger logger) { _lifetime = lifetime; _lifetime.ApplicationStarted.Register(OnStarted); _lifetime.ApplicationStopping.Register(OnStopping); _lifetime.ApplicationStopped.Register(OnStopped); _log = logger; }
private void OnStopped() { _log.LogInformation("OnStopped has been called."); }
private void OnStopping() { _log.LogInformation("OnStopping has been called."); }
private void OnStarted() { _log.LogInformation("OnStarted has been called."); }
public Task StartAsync(CancellationToken cancellationToken) { _log.LogInformation("Start Sample Host"); return Task.CompletedTask; }
public Task StopAsync(CancellationToken cancellationToken) { _log.LogInformation("End Sample Host"); return Task.CompletedTask; }}
3. 应用场景:
日志和监控:记录应用程序启动和停止的时间。触发外部监控工具的通知。
初始化操作:在 ApplicationStarted 中执行启动后的初始化逻辑,如加载缓存数据或运行必要任务。
优雅关闭应用程序:在 ApplicationStopping 事件中释放资源,如数据库连接、文件句柄等。通知外部服务或任务终止运行。


源代码地址:

https://github.com/bingbing-gui/AspNetCore-Skill/tree/master/src/aspnetcore-knowledge-point/generic-host-lifetime


点击这里复制本文地址 以上内容由jaq123整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!

苍茫编程网 © All Rights Reserved.  蜀ICP备2024111239号-21