Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console app won't exit when given ctrl + c in debug mode

Tags:

c#

When I run the below in Release, pressing CTRL + C successfully terminates the application.

When running in Debug, pressing CTRL + C hangs in the while loop below.

Why? Is there a way around this?

static void Main(string[] args)
{
    while (true)
    {
        // Press CTRL + C...
        // When running in Release, the app closes down
        // When running in Debug, it hangs in here
    }
}
like image 561
mariocatch Avatar asked Jan 28 '23 08:01

mariocatch


1 Answers

One way is to achieve this is to use Console.CancelKeyPress

Occurs when the Control modifier key (Ctrl) and either the ConsoleKey.C console key (C) or the Break key are pressed simultaneously (Ctrl+C or Ctrl+Break).

When the user presses either Ctrl+C or Ctrl+Break, the CancelKeyPress event is fired and the application's ConsoleCancelEventHandler event handler is executed. The event handler is passed a ConsoleCancelEventArgs object


Example

private static bool keepRunning = true;

public static void Main(string[] args)
{
   Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
         e.Cancel = true;
         keepRunning = false;
      };

   while (keepRunning) 
   {
      // Do stuff
   }
   Console.WriteLine("exited gracefully");
}
like image 150
TheGeneral Avatar answered Feb 12 '23 21:02

TheGeneral