Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutdown .Netcore IHostedService as Console App

Tags:

c#

.net-core

I have built Generic Host (IHostedService) in .netcore 2.2. I am running HostBuilder as RunConsoleAsync(). RunConsoleAync() will wait for Ctrl + C to close application. I want to close console app as soon as StartAsync() process complete instead of user has to press ctrl + c.

I tried to Invoke StopAsync() with new CancellationToken(true), but it is not helping me.

I developed this as IHostedService, because this app will be deployed on multiple plateform.

like image 350
Kamran Asim Avatar asked Apr 09 '19 09:04

Kamran Asim


People also ask

Is .NET core a console app?

NET Core Console application, open Visual Studio 2017 and select on the menu: File -> New -> Project.. This will open the New Project popup, as shown below. In the New Project popup, expand Installed -> Visual C# in the left pane and select the Console App (. NET Core) template in the middle pane.

What is .NET core IHost?

Run(IHost) Runs an application and blocks the calling thread until host shutdown is triggered and all IHostedService instances are stopped.

What does host RunAsync do?

RunAsync runs the app and returns a Task that completes when the cancellation token or shutdown is triggered.


1 Answers

I assume you have the IHostedService implementation in place. All you need to do is inject IHostApplicationLifetime and use that to stop the application as shown below:

    public class Service : IHostedService
{
    private readonly IHostApplicationLifetime _applicationLifetime;
    public Service(IHostApplicationLifetime applicationLifetime)
    {
        _applicationLifetime = applicationLifetime;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        ...

        _applicationLifetime.StopApplication();
        return Task.CompletedTask;
    }

    ...
}
like image 72
Thulani Chivandikwa Avatar answered Sep 22 '22 22:09

Thulani Chivandikwa