asp.net 核心:IApplicationLifetime.ApplicationStop 未触发



我看过几篇关于IApplicationLifetime的文章,以及在应用程序启动和停止时触发执行的方法,但我可能错过了一些东西,因为它只是没有被触发。以下是我的解决方法:我为kubernetes打开了一个项目模板Container Application,asp.net core 2.2

Program.cs看起来就像创建时一样:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Kubernetes1
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}

Startup.cs如下所示:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Kubernetes1
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//var appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
appLifetime.ApplicationStopping.Register(() => Console.WriteLine("ApplicationStopping called"));
appLifetime.ApplicationStopped.Register(() => Console.WriteLine("ApplicationStopped called"));
app.Run(async (context) =>
{
Console.WriteLine("AAA");
});
}
}
}

我在这里想做的就是在cmd中运行应用程序,然后停止它,看到控制台中打印的2行:

  1. ApplicationStopping已调用
  2. 已调用ApplicationStopped我没能做到。有什么想法吗

在不同的cmd窗口中我键入:Get-Process -Name *dotnet* | Stop-Process

Stop-Process终止进程,跳过应用程序可能具有的任何优雅关闭行为。

IApplicationLifetime谈到应用程序停止时,它指的是应用程序被正常关闭。根据应用程序的启动方式,有几种方法可以触发:

  • 当应用程序在控制台中运行时:CTRL+C。例如,当通过dotnet run运行或直接运行已编译的可执行文件时
  • 当应用程序在IIS中运行时:停止网站或应用程序池
  • 当应用程序作为Windows服务运行时:停止服务

最新更新