Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop HostedService programmatically? [duplicate]

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?

like image 599
Я TChebur Avatar asked May 14 '26 13:05

Я TChebur


1 Answers

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.

like image 59
Kirk Larkin Avatar answered May 19 '26 04:05

Kirk Larkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!