|
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; |
| 1 | +using Microsoft.Extensions.Logging; |
4 | 2 |
|
5 | 3 | namespace ConnyConsole.Infrastructure;
|
6 | 4 |
|
7 |
| -public sealed class CancellationTokenFactory(ILogger<CancellationTokenFactory> logger) : IDisposable |
| 5 | +/// <inheritdoc/> |
| 6 | +public sealed class ConsoleCancellationTokenSource(ILogger<ConsoleCancellationTokenSource> logger) |
| 7 | + : CancellationTokenSource |
8 | 8 | {
|
9 |
| - private bool _gracefulCancel = true; |
10 |
| - private readonly CancellationTokenSource _cancellationTokenSource = new(); |
11 |
| - |
12 |
| - public CancellationToken CancellationToken => _cancellationTokenSource.Token; |
13 |
| - |
14 |
| - /// <summary> |
15 |
| - /// Releases the resources used by this <see cref="CancellationTokenSource"/> |
16 |
| - /// </summary> |
17 |
| - /// <remarks> |
18 |
| - /// This method is not thread-safe for any other concurrent calls. |
19 |
| - /// </remarks> |
20 |
| - public void Dispose() => _cancellationTokenSource.Dispose(); |
| 9 | + private bool _isGracefulCancelled = true; |
21 | 10 |
|
22 | 11 | /// <summary>
|
23 | 12 | /// Creates a <see cref="ConsoleCancelEventHandler"/> for a gracefully (first Ctrl+C) or forced (second Ctrl+C) application exit.
|
24 | 13 | /// It can be registered on the <see cref="Console.CancelKeyPress"/> event.
|
25 | 14 | /// </summary>
|
26 | 15 | /// <param name="timeout">The timeout after which the app is forcibly terminated.</param>
|
27 | 16 | /// <returns>The configured <see cref="ConsoleCancelEventHandler"/> event.</returns>
|
28 |
| - public ConsoleCancelEventHandler CreateHandler(TimeSpan timeout) |
| 17 | + /// <remarks>This method is based on https://medium.com/@sawyer.watts/a-beginners-guide-to-net-s-hostbuilder-part-2-cancellation-857ae3e6ff02</remarks> |
| 18 | + public ConsoleCancelEventHandler CreateCancellationHandler(TimeSpan timeout) |
29 | 19 | {
|
30 | 20 | return (_, cancelEvent) =>
|
31 | 21 | {
|
32 |
| - if (_gracefulCancel) |
| 22 | + if (_isGracefulCancelled) |
33 | 23 | {
|
34 | 24 | logger.LogInformation(
|
35 |
| - "Received interrupt signal, attempting to shut down gracefully but will force-close in {Seconds} seconds. Send again to immediately force-close.",timeout.TotalSeconds); |
| 25 | + "Received interrupt signal, attempting to shut down gracefully but will force-close in {Seconds} seconds. Send again to immediately force-close.", |
| 26 | + timeout.TotalSeconds); |
36 | 27 |
|
37 |
| - _cancellationTokenSource.Cancel(); |
| 28 | + Cancel(); |
38 | 29 | cancelEvent.Cancel = true;
|
39 |
| - _gracefulCancel = false; |
| 30 | + _isGracefulCancelled = false; |
40 | 31 |
|
41 | 32 | ForceExitAfterTimeout((int)timeout.TotalMilliseconds);
|
42 | 33 | }
|
|
0 commit comments