Home >Backend Development >C++ >How Can I Gracefully Handle Ctrl C (SIGINT) in a C# Console Application?
When working with C# console applications, it may become necessary to trap the Ctrl C (SIGINT) keystroke to perform specific cleanup tasks before the application exits. This article delves into the best practices for capturing SIGINT in C# console applications.
The recommended approach is to subscribe to the Console.CancelKeyPress event, which triggers when the user presses Ctrl C. By providing a delegate to this event, you can execute cleanup code before the application exits.
public static void Main(string[] args) { Console.CancelKeyPress += delegate { // Cleanup code }; while (true) {} }
However, this approach has limitations. Code placed after the cleanup delegate may not execute when Ctrl C is pressed.
In scenarios where immediate interruption is undesirable, you may want to gracefully exit the application when a calculation or task is complete. Using set-reset events allows you to control the exit process:
private static bool keepRunning = true; public static void Main(string[] args) { Console.CancelKeyPress += (sender, e) => { e.Cancel = true; keepRunning = false; }; while (keepRunning) { // Task execution } Console.WriteLine("Exited gracefully"); }
When Ctrl C is pressed, e.Cancel is set to true, preventing immediate exit. The keepRunning variable is set to false, causing the while loop to terminate after the current task completes. This allows the application to exit gracefully.
The above is the detailed content of How Can I Gracefully Handle Ctrl C (SIGINT) in a C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!