就像标题所说,我有兴趣了解程序是如何终止的。 host.Run()之后的行似乎永远不会执行。
我的具体目标是在关闭网站时处理KeepAliveTimer,以便所有实现该目标的答案都是受欢迎的。
我想我可以将所有Main()包装在一个使用块中,但考虑到我在这里的问题,我仍然不相信它会起作用。我过去曾经遇到计时器内存泄漏的问题,因此我的恐惧症。
public class Program
{
private static Timer KeepAliveTimer;
private static HttpClient client = new HttpClient();
public static void Main(string[] args)
{
KeepAliveTimer = new Timer(x => CallAPI(), null, 0, 5000);
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
KeepAliveTimer.Dispose(); // Not happening
}
private static void CallAPI()
{
// etc...
}
}
修改的
根据Tseng发表的评论和链接
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
// also does not work when IApplicationLifetime is injected
var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStopping.Register(() => {
KeepAliveTimer.Dispose(); // not called
});
appLifetime.ApplicationStopped.Register(() => {
KeepAliveTimer.Dispose(); // not called
});
}