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.

while (true)
{
if (!Console.KeyAvailable)
{
continue;
}
var input = Console.ReadKey(true);
if (input.Modifiers != ConsoleModifiers.Control)
{
continue;
}
if (input.Key == ConsoleKey.S)
{
Server?.Dispose();
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With