|
| 1 | +// This class function is based on https://medium.com/@sawyer.watts/a-beginners-guide-to-net-s-hostbuilder-part-2-cancellation-857ae3e6ff02 |
| 2 | + |
| 3 | +using Microsoft.Extensions.Logging; |
| 4 | + |
| 5 | +namespace ConnyConsole.Infrastructure; |
| 6 | + |
| 7 | +public sealed class CancellationTokenFactory(ILogger<CancellationTokenFactory> logger) |
| 8 | +{ |
| 9 | + private bool _gracefulCancel = true; |
| 10 | + private readonly CancellationTokenSource _cancellationTokenSource = new(); |
| 11 | + |
| 12 | + public CancellationToken CancellationToken => _cancellationTokenSource.Token; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Creates a <see cref="ConsoleCancelEventHandler"/> for a gracefully (first Ctrl+C) or forced (second Ctrl+C) application exit. |
| 16 | + /// It can be registered on the <see cref="Console.CancelKeyPress"/> event. |
| 17 | + /// </summary> |
| 18 | + /// <param name="timeout">The timeout after which the app is forcibly terminated.</param> |
| 19 | + /// <returns>The configured <see cref="ConsoleCancelEventHandler"/> event.</returns> |
| 20 | + public ConsoleCancelEventHandler CreateHandler(TimeSpan timeout) |
| 21 | + { |
| 22 | + return (_, cancelEvent) => |
| 23 | + { |
| 24 | + if (_gracefulCancel) |
| 25 | + { |
| 26 | + logger.LogInformation( |
| 27 | + $"Received interrupt signal, attempting to shut down gracefully but will force-close in {timeout.TotalSeconds} seconds. Send again to immediately force-close."); |
| 28 | + |
| 29 | + _cancellationTokenSource.Cancel(); |
| 30 | + cancelEvent.Cancel = true; |
| 31 | + _gracefulCancel = false; |
| 32 | + |
| 33 | + ForceExitAfterTimeout((int)timeout.TotalMilliseconds); |
| 34 | + } |
| 35 | + else |
| 36 | + { |
| 37 | + logger.LogInformation("Second interrupt received, force-closing the app"); |
| 38 | + } |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Waits a defined timeout in milliseconds, afterward enforces the application exit. |
| 44 | + /// </summary> |
| 45 | + private void ForceExitAfterTimeout(int timeoutInMilliseconds) |
| 46 | + { |
| 47 | + _ = new Timer( |
| 48 | + _ => |
| 49 | + { |
| 50 | + logger.LogInformation("Timeout reached, force-closing app."); |
| 51 | + Environment.Exit(0); |
| 52 | + }, |
| 53 | + state: null, |
| 54 | + dueTime: timeoutInMilliseconds, |
| 55 | + period: 0); |
| 56 | + } |
| 57 | +} |
0 commit comments