I'm building a dotnet core HostedService app. I need to stop application after some period of time.
How can I stop it?
I've tried to add to StartAsync method
await Task.Delay(5000);
Environment.Exit(0);
Main:
static Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<EventsService>();
})
.UseLogging();
return hostBuilder.RunConsoleAsync();
}
it doesn't work. How can I correctly stop it?
RunConsoleAsync
accepts a CancellationToken
. You can create a CancellationTokenSource
that signals cancellation after a given number of milliseconds:
var cancellationTokenSource = new CancellationTokenSource(5000);
return hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);
With this, the application shuts down after roughly five seconds.