Console.ReadKey不可靠

Console.ReadKey not reliable

我有以下代码,它等待用户通过箭头键输入移动或退出以结束程序。

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
}

但是,它只是偶尔确认我的输入。例如,如果我快速点击退出键,大多数时候什么都不会发生。所以 Console.ReadKey 方法对我来说似乎非常不可靠。什么是更好的选择?

您拨打 ReadKey 的次数过多

这是一个更好的模式

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

}

// 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;
}