ASP.NET Core Startup.cs 中的 Kestrel 关闭功能 [英] Kestrel shutdown function in Startup.cs in ASP.NET Core
问题描述
使用Microsoft.AspNet.Server.Kestrel
时是否有关机功能?ASP.NET Core
(以前的ASP.NET vNext
)显然有一个启动序列,但没有提到关闭序列以及如何处理干净的关闭.
Is there a shutdown function when using Microsoft.AspNet.Server.Kestrel
? ASP.NET Core
(formerly ASP.NET vNext
) clearly has a Startup sequence, but no mention of shutdown sequence and how to handle clean closure.
推荐答案
在 ASP.NET Core 中,您可以注册到 IApplicationLifetime
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
还公开了 ApplicationStopped
和 ApplicationStarted
的取消令牌以及 StopApplication()
方法以停止应用程序.
IApplicationLifetime
is also exposing cancellation tokens for ApplicationStopped
and ApplicationStarted
as well as a StopApplication()
method to stop the application.
来自评论@Horkrine
对于 .NET Core 3.0+,建议改用 IHostApplicationLifetime,因为 IApplicationLifetime 将很快被弃用.其余的仍然会像上面写的那样使用新服务
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
这篇关于ASP.NET Core Startup.cs 中的 Kestrel 关闭功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!