Handling CancelKeyPress using a CancellationToken
You sometimes need to detect when a console application is closing to perform some cleanup. Console.CancelKeyPress
allows registering a callback when a user press Ctrl+C or Ctrl+Break. This event can prevent the application from closing, so you can take a few seconds to perform the cleanup before actually terminating the application. The idea of this post is to use Console.CancelKeyPress
to create a CancellationToken
that can be used to cancel current asynchronous operations.
public class Program
{
public static async Task Main(string[] args)
{
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
// We'll stop the process manually by using the CancellationToken
e.Cancel = true;
// Change the state of the CancellationToken to "Canceled"
// - Set the IsCancellationRequested property to true
// - Call the registered callbacks
cts.Cancel();
};
await MainAsync(args, cts.Token);
}
private static async Task MainAsync(string[] args, CancellationToken cancellationToken)
{
try
{
// code using the cancellation token
Console.WriteLine("Waiting");
await Task.Delay(10_000, cancellationToken);
}
catch (OperationCanceledException)
{
Console.WriteLine("Operation canceled");
}
}
}
If you need to handle more cases than the CancelKeyPress
, you can check this post about detecting console closing in .NET. It uses the SetConsoleCtrlHandler
method to detect when the console is closing.
Do you have a question or a suggestion about this post? Contact me!