In ASP.NET Core you can register to the cancellation tokens provided by IApplicationLifetime
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime)
{
applicationLifetime.ApplicationStopping.Register(OnShutdown);
}
private void OnShutdown()
{
// Do your cleanup here
}
}
IApplicationLifetime
is also exposing cancellation tokens for ApplicationStopped
and ApplicationStarted
as well as a StopApplication()
method to stop the application.
For .NET Core 3.0+
From comments @Horkrine
For .NET Core 3.0+ it is recommended to use IHostApplicationLifetime instead, as IApplicationLifetime will be deprecated soon. The rest will still work as written above with the new service
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…