How to stop/exit/terminate dotnet core HostBuilder console application programmatically?

How to stop/exit/terminate dotnet core HostBuilder console application programmatically?

To stop/exit/terminate a .NET Core HostBuilder console application programmatically, you can make use of the IHostApplicationLifetime interface provided by the Microsoft.Extensions.Hosting.Abstractions package.

Here's an example of how you can use it:

using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp { class Program { static async Task Main(string[] args) { var hostBuilder = new HostBuilder() .ConfigureServices((hostContext, services) => { services.AddSingleton<IHostLifetime, ConsoleLifetime>(); services.AddHostedService<MyService>(); }); await hostBuilder.RunConsoleAsync(); } } public class MyService : IHostedService { private readonly IHostApplicationLifetime _appLifetime; public MyService(IHostApplicationLifetime appLifetime) { _appLifetime = appLifetime; } public Task StartAsync(CancellationToken cancellationToken) { Console.WriteLine("MyService started."); // Stop the application after 5 seconds _appLifetime.StopApplication(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("MyService stopped."); return Task.CompletedTask; } } internal class ConsoleLifetime : IHostLifetime { private readonly TaskCompletionSource<object> _delayStart = new TaskCompletionSource<object>(); public Task WaitForStartAsync(CancellationToken cancellationToken) { cancellationToken.Register(() => _delayStart.TrySetCanceled()); return _delayStart.Task; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } } 

In this example, the MyService implements the IHostedService interface and injects the IHostApplicationLifetime interface in the constructor. The StartAsync method sets a delay of 5 seconds and then calls the _appLifetime.StopApplication() method to stop the application.

The ConsoleLifetime class implements the IHostLifetime interface, which is responsible for starting and stopping the host. The WaitForStartAsync method returns a Task that completes when the host is started. The StopAsync method is called when the host is stopped, and it returns a completed Task.

Examples

  1. "Gracefully stop HostBuilder console application in .NET Core"

    • Description: Learn how to gracefully stop a .NET Core console application using HostBuilder.

    • Code:

      // Request application termination using (var cts = new CancellationTokenSource()) { var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); Console.CancelKeyPress += (sender, args) => { args.Cancel = true; cts.Cancel(); }; await host.RunAsync(cts.Token); } 
  2. "Exit console application with specific exit code in HostBuilder .NET Core"

    • Description: Explore ways to exit a .NET Core console application with a specific exit code using HostBuilder.

    • Code:

      // Exit with a specific exit code var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); await host.RunAsync(); Environment.Exit(ExitCode); // Replace ExitCode with your desired exit code 
  3. "Terminate HostBuilder console application programmatically .NET Core"

    • Description: Find ways to programmatically terminate a .NET Core console application using HostBuilder.

    • Code:

      // Terminate the application var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); await host.RunAsync(); // Place termination logic here 
  4. "Stop HostBuilder application when a condition is met .NET Core"

    • Description: Learn how to stop a .NET Core console application using HostBuilder when a specific condition is met.

    • Code:

      // Stop the application when a condition is met var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); // Check condition and stop if (conditionMet) { await host.RunAsync(); } 
  5. "Exit console application on specific event in .NET Core"

    • Description: Explore methods to exit a .NET Core console application using HostBuilder in response to a specific event.

    • Code:

      // Exit on a specific event var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); // Subscribe to the specific event and exit // Replace YourEvent with the event you are handling YourEvent += (sender, args) => Environment.Exit(ExitCode); await host.RunAsync(); 
  6. "Terminate HostBuilder application on unhandled exception .NET Core"

    • Description: Learn how to terminate a .NET Core console application using HostBuilder when an unhandled exception occurs.

    • Code:

      // Terminate on unhandled exception var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); AppDomain.CurrentDomain.UnhandledException += (sender, args) => Environment.Exit(ExitCode); await host.RunAsync(); 
  7. "Stop HostBuilder console application on user input .NET Core"

    • Description: Explore ways to stop a .NET Core console application using HostBuilder based on user input.

    • Code:

      // Stop on user input var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); Environment.Exit(ExitCode); // Replace ExitCode with your desired exit code 
  8. "Gracefully exit HostBuilder console app on service completion .NET Core"

    • Description: Learn how to gracefully exit a .NET Core console application using HostBuilder when a specific service or task completes.

    • Code:

      // Gracefully exit on service completion var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); var task = SomeServiceAsync(); await task; Environment.Exit(ExitCode); // Replace ExitCode with your desired exit code 
  9. "Stop HostBuilder application after a certain duration .NET Core"

    • Description: Find ways to stop a .NET Core console application using HostBuilder after a certain duration.

    • Code:

      // Stop after a certain duration var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); await Task.Delay(TimeSpan.FromSeconds(DurationInSeconds)); Environment.Exit(ExitCode); // Replace ExitCode with your desired exit code 
  10. "Terminate HostBuilder console application on specific condition .NET Core"

    • Description: Learn how to terminate a .NET Core console application using HostBuilder when a specific condition is met.

    • Code:

      // Terminate on a specific condition var host = new HostBuilder() .ConfigureServices((hostContext, services) => { // Configure services }) .Build(); while (!conditionMet) { // Application logic } Environment.Exit(ExitCode); // Replace ExitCode with your desired exit code 

More Tags

spring-mybatis quantum-computing sapui5 apache-tez wcf-web-api core-animation kubernetes-helm xpath-1.0 google-hangouts xhtml

More C# Questions

More Everyday Utility Calculators

More Geometry Calculators

More Dog Calculators

More Electronics Circuits Calculators