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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With