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.
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.
Run(IHost) Runs an application and blocks the calling thread until host shutdown is triggered and all IHostedService instances are stopped.
RunAsync runs the app and returns a Task that completes when the cancellation token or shutdown is triggered.
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;
}
...
}
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