Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

High CPU usage in console application

I want to constantly wait for a key combination to be pressed in my console application, but the way I am currently doing it seems to use a lot of CPU while the process is running.

For such a basic task it feels like there should be a better way to do this, but I'm unsure of what that is, I profiled my application with dotTrace and found that the only hot spot was this code below.

enter image description here

while (true)
{
    if (!Console.KeyAvailable)
    {
        continue;
    }

    var input = Console.ReadKey(true);

    if (input.Modifiers != ConsoleModifiers.Control)
    {
        continue;
    }

    if (input.Key == ConsoleKey.S)
    {
        Server?.Dispose();
    }
}
like image 295
ropuxil Avatar asked Feb 17 '26 10:02

ropuxil


1 Answers

If you are fine using standard Ctrl+C for exit instead of Ctrl+S you can use simple ReadKey. And make sure TreatControlCAsInput is set, oterwise, the application will just be killed.

  static void Main(string[] args)
  {
     // important!!!
     Console.TreatControlCAsInput = true;

     while (true)
     {
        Console.WriteLine("Use CTRL+C to exit");
        var input = Console.ReadKey();

        if (input.Key == ConsoleKey.C && input.Modifiers == ConsoleModifiers.Control)
        {
           break;
        }
     }

     // Cleanup
     // Server?.Dispose();
  }
like image 186
Euphoric Avatar answered Feb 19 '26 23:02

Euphoric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!