2

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Я TChebur
  • 366
  • 6
  • 23

1 Answers1

2

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.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203