How to stop/exit/terminate dotnet core HostBuilder console application programmatically?

You can use IHostApplicationLifetime to stop running of your application, you can access it from constructor and call StopApplication() method.

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

then StopApplication()

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

Edited to use IHostApplicationLifetime as IApplicationLifetime is deprected.


Even though you are using the HostBuilder to register all dependencies in your application, you don't have to use the IHost to execute a cmd line app. You can just execute your app via creating a service scope like so

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
 }