Search code examples
c#asp.net-coreasp.net-core-hosted-services

How to stop HostedService programmatically?


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?


Solution

  • 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.