0

I have a console application which stores my input when calling ReadKey() before that line executes:

static void Main(string[] args)
{
    Console.WriteLine("Beginning long pause...");
    Thread.Sleep(6000);
    var input = Console.ReadKey();

    Console.WriteLine("You pressed: " + input.Key.ToString());
    Console.ReadLine();
}

* Small note: You'll need to add using System.Threading;.

Now, set a breakpoint on var input = Console.ReadKey();. Run the application and immediately press any key. After a few seconds, the breakpoint will trigger. Continue, and the application will print out the key you pressed before the breakpoint triggered.

How / why does this happen, and how can I make it so my application won't "remember" any input until ReadKey() actually executes?

sab669
  • 3,984
  • 8
  • 38
  • 75
  • 2
    The keystroke waits in the input buffer until you read it. You might try [discarding everything in the buffer immediately after Sleep, like in this answer](http://stackoverflow.com/a/3769828/424129). – 15ee8f99-57ff-4f92-890c-b56153 Jan 09 '17 at 15:51
  • But bear in mind that users like to be able to type ahead, even if the program is currently busy. it can be annoying for a program to throw away my type ahead, so I then have to enter it again. – Polyfun Jan 09 '17 at 16:14
  • @Polyfun It's my own personal utility to make dev work a little easier, so that's not too much of a concern – sab669 Jan 09 '17 at 16:34

0 Answers0