CTRL-C Delay in C# Console

63 Views Asked by At

While my C# code running, I am pushing CTRL-C to stop it running. However, it stops after roughly 1 second and acts according to the "default" case of switch.

I'd like to make it stop instantly. What am I missing? I have a few such switches, this is happening to all of them. Apart from the switches, the do-while loops also have the same issue. They all process the CTRL-C input as kind of default case, printing Input Error message and then preventing the program from further execution.

    public static void ManageMainMenu() 
    {
        string? userInput;
        do
        {
            Console.WriteLine("-----------------------------------------------------------");
            Console.WriteLine("Please select your preferred option below:");
            Console.WriteLine("1. Foods");
            Console.WriteLine("2. Drinks");
            Console.WriteLine("3. Exit");

            userInput = Console.ReadLine()?.Trim(); 
            switch (userInput) 
            {
                case "1":  
                    MenuManagement.ManageFoods(); 
                    break;
                case "2": 
                    MenuManagement.ManageDrinks();
                    break;
                case "3": 
                    Environment.Exit(0);
                    break;
                default: 
                    Console.WriteLine("Invalid Input! Please choose from the options above (1, 2, 3): ");
                    break;
            }
        } while (userInput != "3"); 
    }
}

And here is what I'm getting when pushing CTRL-C right away:

Invalid Input! Please choose from the options above (1, 2, 3): 
-----------------------------------------------------------
Please select your preferred option below:
1. Foods
2. Drinks
3. Exit

Process finished with exit code 0.
0

There are 0 best solutions below