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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-30 20:52:14449browse

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

Handling Ctrl C (SIGINT) in C# Console Applications

In C#, trapping Ctrl C (SIGINT) allows for necessary cleanups before gracefully exiting a console application. The Console.CancelKeyPress event provides a means to handle this interruption.

Using Console.CancelKeyPress

The following code demonstrates how to use the CancelKeyPress event:

public static void Main(string[] args)
{
    Console.CancelKeyPress += delegate {
        // Perform clean-up actions
    };

    while (true) {}
}

When the user presses Ctrl C, the delegate code executes, initiating the clean-up process, and the program exits immediately.

Specific Use Cases

In scenarios where immediate cessation of calculations is undesirable, an alternate approach is recommended:

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object? sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };
        
        while (MainClass.keepRunning) {
            // Perform small chunks of work
        }
        Console.WriteLine("exited gracefully");
    }
}

This implementation sets the e.Cancel flag to true, preventing immediate program termination. Instead, the keepRunning variable is set to false, allowing the while loop to exit after any ongoing calculations complete. This approach facilitates graceful program termination.

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

Statement:
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