如何以编程方式停止/退出/终止dotnet核心HostBuilder控制台应用程序?

时间:2019-02-27 18:15:46

标签: .net-core console-application

我正在尝试创建一个dotnet核心控制台应用程序。该应用程序是一个简单的实用程序应用程序,应启动,运行并退出。 使用Visual Studio生成的标准控制台应用程序模板很容易实现。 但是如今,我们有了HostBuilder,它似乎更具吸引力,因为它带来了WebHostBuilder,DI,Loggin等的统一体验。

但是,看起来这种方法仅适用于长期运行的后台服务。它将开始并永远坐着直到外部终止事件(例如Ctrl-C)。

是否可以从内部结束这种类型的应用程序?

4 个答案:

答案 0 :(得分:3)

您可以使用IApplicationLifeTime停止运行应用程序,可以从构造函数访问它并调用StopApplication()方法。

IApplicationLifetime _lifeTime;
public MyClass(IApplicationLifetime lifeTime)
{
    _lifeTime = lifeTime;
}

然后使用StopApplication()

public void Exit()
{
    _lifeTime.StopApplication();
}

答案 1 :(得分:1)

我遇到了同样的问题。我需要终止我的网络服务。所以我使用了类似于解决方案标记答案的方法,但服务并没有立即终止,而是继续执行命令。所以我需要在出口后立即返回。

我的杀戮方法:

private void Exit(IHostApplicationLifetime lifetime, ExitCode code)
{
    Environment.ExitCode = (int)code; //just shows in debug
    lifetime.StopApplication();
    // add log if you want to see the exitCode
}

Startup.cs 中的 Configure 方法

public void Configure(IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
    // code
    bool hasPendingMigrations = HasDatabasePendingMigrations(app);
    if (hasPendingMigrations)
    {
        Exit(lifetime, ExitCode.HasPendingMigrations);
        // we need to return explicit after exit
        return;
    }
    // code
}

你需要回来。 ExitCode 是自定义创建的枚举。

答案 2 :(得分:0)

即使您正在使用HostBuilder在应用程序中注册所有依赖项,也不必使用IHost执行cmd line应用程序。您可以通过创建这样的服务范围来执行您的应用

HostBuilder hostbuilder = new HostBuilder();
builder.ConfigureServices(ConfigureServices); //Configure all services for your application here
IHost host = hostbuilder .Build();

using (var scope = host.Services.CreateScope())
{
   var myAppService = scope.ServiceProvider.GetService(typeof(IMyAppServiceToRun)) as IMyAppServiceToRun; //Use IHost DI container to obtain instance of service to run & resolve all dependencies

   await myAppService.StartAsync(CancellationToken.None); // Execute your task here
 }

答案 3 :(得分:0)

1-在UseConsoleLifetime()中构建主机时使用Program.cs

Program.cs:

Host.CreateDefaultBuilder(args).UseConsoleLifetime(opts => opts.SuppressStatusMessages = true);

2-已注册的ApplicationStopped事件。这样您就可以通过调用当前进程的Kill()方法来强行终止应用程序。

Startup.cs:

public void Configure(IHostApplicationLifetime appLifetime) {
 appLifetime.ApplicationStarted.Register(() => {
  Console.WriteLine("Press Ctrl+C to shut down.");
 });

 appLifetime.ApplicationStopped.Register(() => {
  Console.WriteLine("Terminating application...");
  System.Diagnostics.Process.GetCurrentProcess().Kill();
 });
}