Home > Backend Development > C++ > How Can I Gracefully Handle Ctrl C Interrupts in a C# Console Application?

How Can I Gracefully Handle Ctrl C Interrupts in a C# Console Application?

Barbara Streisand
Release: 2024-12-27 09:38:13
Original
1002 people have browsed it

How Can I Gracefully Handle Ctrl C Interrupts in a C# Console Application?

Trapping Ctrl C (SIGINT) in a C# Console Application

To gracefully handle the interruption of a C# console application by pressing Ctrl C (SIGINT), the Console.CancelKeyPress event can be utilized.

Using the Console.CancelKeyPress Event:

The Console.CancelKeyPress event is raised when the user presses Ctrl C. By registering an event handler to this event, code can be executed before the program terminates.

Console.CancelKeyPress += delegate {
    // Perform cleanup operations
};
Copy after login

When Ctrl C is pressed, the code within the event handler will execute, allowing for essential cleanup tasks to be completed. It's important to note that no code after the delegate will be executed.

Handling Complex Scenarios:

For situations where the immediate termination of a task is not practical, a different approach can be employed. The following code demonstrates how to tell the program to exit gracefully after a calculation is completed:

bool keepRunning = true;

Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
    e.Cancel = true;
    keepRunning = false;
};

while (keepRunning) {
    // Perform work in small chunks
}
Copy after login

By setting e.Cancel to true, the execution continues after the event handler. The keepRunning variable is set to false when Ctrl C is pressed, causing the program to gracefully exit.

The above is the detailed content of How Can I Gracefully Handle Ctrl C Interrupts in a C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template