정리를 수행하기 위해 콘솔 애플리케이션이 닫히는 시점을 감지해야 하는 경우가 있습니다. Console.CancelKeyPress
를 사용하면 Ctrl+C
또는 Ctrl+Break
를 누를 때 콜백을 등록할 수 있습니다. 이 이벤트를 사용하면 애플리케이션이 닫히는 것을 방지할 수 있으므로 실제로 애플리케이션을 종료하기 전에 몇 초 동안 정리를 수행할 수 있습니다. 이 포스트의 아이디어는 Console.CancelKeyPress
를 사용하여 현재 비동기 작업을 취소하는 데 사용할 수 있는 CancellationToken
을 생성하는 것입니다.
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");
}
}
}
CancelKeyPress
보다 더 많은 경우를 처리해야 하는 경우 .NET에서 콘솔 종료를 감지하는 방법에 대한 이 게시물을 확인할 수 있습니다. 콘솔이 닫히는 시점을 감지하기 위해 SetConsoleCtrlHandler
메서드를 사용합니다.