Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to create a dotnet core console app. The app is a simply utility app and should start, do its thing and exit. It's easy to achieve using standard console application template generated by Visual Studio. But these days we have HostBuilder which seems to be more attractive because it brings unifying experience with WebHostBuilder, DI, Loggin, etc.

But it looks like this approach only designed for the long running background services. It will start and sit forever until the external termination event (like Ctrl-C).

Is there a way to end this type of application from the inside?

like image 609
rook Avatar asked Feb 27 '19 18:02

rook


1 Answers

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.

like image 86
amirhossein ghorbani Avatar answered Oct 01 '22 04:10

amirhossein ghorbani