可以使用 IApplicationLifetime 接口中的 StopApplication() 方法来停止应用程序的运行,并利用 Microsoft.Extensions.Hosting 中的 HostExtensions.WaitForShutdown() 方法等待应用程序关闭。具体的代码示例如下:
using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MyApp
{
public class Program
{
private static IHostApplicationLifetime _appLifetime;
public static void Main(string[] args)
{
IWebHost host = CreateWebHostBuilder(args).Build();
_appLifetime = host.Services.GetService();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddSingleton();
});
public class MyService : IHostedService
{
private readonly IApplicationLifetime _appLifetime;
public MyService(IApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
public void Start()
{
// do some long-running operation
if (someCondition)
_appLifetime.StopApplication();
}
public void Stop()
{
// cleanup code
}
}
}
}
上述示例中,我们在 Program.Main() 方法中获取了 IHostApplicationLifetime 接口的实例,并在应用程序启动后调用了 host.Run() 方法来运行应用程序。而在 MyService.Start() 方法中,我们可以编写一些长时间运行的代码。如果我们在其中检测到某个条件(someCondition),则会停止应用程序的运行。为此,我们使用了 _appLifetime.StopApplication() 方法。
此外,我们还可以使用 HostExtensions.WaitForShutdown() 方法来等待应用程序关闭。如需使用此方法,请在 Program.Main() 方法的 host.Run() 后面添加以下一行代码:
_appLifetime.ApplicationStopped.WaitHandle.WaitOne();