Shutdown .Netcore IHostedService as Console App

Shutdown .Netcore IHostedService as Console App

To properly shut down an IHostedService in a .NET Core console app, you can use the CancellationToken passed to the StopAsync method of the IHostedService interface.

Here's an example:

using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ConsoleApp { class Program { static async Task Main(string[] args) { var hostBuilder = new HostBuilder() .ConfigureServices((hostContext, services) => { services.AddHostedService<MyHostedService>(); }); using (var host = hostBuilder.Build()) { await host.StartAsync(); Console.WriteLine("Press any key to stop the hosted service"); Console.ReadKey(); // Request cancellation of the hosted service var cts = new CancellationTokenSource(); cts.Cancel(); // Wait for the hosted service to stop gracefully await host.StopAsync(cts.Token); } } } public class MyHostedService : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine("MyHostedService started"); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("MyHostedService stopped"); return Task.CompletedTask; } } } 

In this example, the Main method creates an instance of MyHostedService and registers it as a hosted service using AddHostedService method.

The using block ensures that the host object is properly disposed after it has finished running.

When the user presses a key, the StopAsync method is called on the hosted service by passing a CancellationToken that has been cancelled. This allows the hosted service to gracefully shut down.

Finally, the StopAsync method of the hosted service writes a message to the console to indicate that it has stopped.

Examples

  1. "Shutdown .NET Core IHostedService gracefully console app"

    • Description: Find out how to gracefully shutdown a .NET Core console application hosting an IHostedService.
    • Code:
      using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; class Program { static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var serviceScope = host.Services.CreateScope()) { var services = serviceScope.ServiceProvider; var myService = services.GetRequiredService<IMyService>(); // Replace with your service type var cancellationTokenSource = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; cancellationTokenSource.Cancel(); }; await host.RunAsync(cancellationTokenSource.Token); // Additional cleanup logic if needed myService.Cleanup(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<MyService>(); // Replace with your hosted service }); } public interface IMyService : IHostedService { void Cleanup(); } public class MyService : IMyService { public Task StartAsync(CancellationToken cancellationToken) { // Your startup logic return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { // Your shutdown logic return Task.CompletedTask; } public void Cleanup() { // Additional cleanup logic } } 
  2. "C# shutdown IHostedService console app SIGTERM"

    • Description: Implement shutdown handling for a .NET Core console application hosting an IHostedService in response to the SIGTERM signal.
    • Code:
      using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; class Program { static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var serviceScope = host.Services.CreateScope()) { var services = serviceScope.ServiceProvider; var myService = services.GetRequiredService<IMyService>(); // Replace with your service type var shutdownCts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, e) => { e.Cancel = true; shutdownCts.Cancel(); }; AppDomain.CurrentDomain.ProcessExit += (sender, e) => { shutdownCts.Cancel(); }; AssemblyLoadContext.Default.Unloading += context => { shutdownCts.Cancel(); }; await host.RunAsync(shutdownCts.Token); // Additional cleanup logic if needed myService.Cleanup(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { services.AddHostedService<MyService>(); // Replace with your hosted service }); } public interface IMyService : IHostedService { void Cleanup(); } public class MyService : IMyService { public Task StartAsync(CancellationToken cancellationToken) { // Your startup logic return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { // Your shutdown logic return Task.CompletedTask; } public void Cleanup() { // Additional cleanup logic } } 

More Tags

yaxis variable-initialization decompiling css-transforms gnu-coreutils cassandra-cli cell-formatting jquery-steps code-readability referrer

More C# Questions

More Other animals Calculators

More Cat Calculators

More Stoichiometry Calculators

More Trees & Forestry Calculators