Search code examples
c#.netconsoleconsole.readkeyreadkey

Console.ReadKey not reliable


I have the following code, which waits for user input via arrow keys to move, or escape to end the program.

Console.WriteLine(startNode.Render(true));
LevelState currentNode = startNode;
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
{
    if (Console.ReadKey(true).Key == ConsoleKey.UpArrow)
    {
        Console.WriteLine("up");
        LevelState move = currentNode.StepInDirection(CardinalDirection.Up);
        if (move != null)
        {
            currentNode = move;
            Console.WriteLine(currentNode.Render(true));
        }
    }
    //ditto for the other 3 directions
}

However, it only occasionally acknowledges my input. If I quickly tap the escape key, for example, most of the time nothing happens. So the Console.ReadKey method seems extremely unreliable to me. What is a better alternative?


Solution

  • You are calling ReadKey too many times

    This is a better pattern

    ConsoleKey key;
    while ((key = Console.ReadKey(true).Key) != ConsoleKey.Escape)
    {
       if (key == ConsoleKey.UpArrow)
       {
          ///
       }
       //ditto for the other 3 directions
    
    }
    

    or

    // read key once
    ConsoleKey key = Console.ReadKey(true).Key;
    while (key != ConsoleKey.Escape)
    {
       if (key == ConsoleKey.UpArrow)
       {
          ///
       }
    
       //ditto for the other 3 directions
       key = Console.ReadKey(true).Key;
    }