0

I want to program wait for a span of 1 second for the user input, if there is none then do some part of code, otherwise break out of the loop, i have an example below:

while (true)
{
    while (!Console.KeyAvailable) {
         Console.WriteLine("Waiting for an input");

         Thread.Sleep(1000);
    }
    Console.WriteLine("Input made");
}

The problem is, that after the input is made Console.KeyAvailable property is still in true value, so it will be outputting "Input made" forever, is there any alternative to Console.KeyAvailable or how do i make it work more that once?

s4g
  • 15
  • 4

1 Answers1

1

You can clear the input buffer again with Console.ReadKey(true).

while (true)
{
    while (!Console.KeyAvailable) {
         Console.WriteLine("Waiting for an input");

         Thread.Sleep(1000);
    }
    Console.WriteLine("Input made");
    //If you dont need the key Info, you can also just write Console.ReadKey(true)
    var keyInfo = Console.ReadKey(true);
}
EnderLuca
  • 66
  • 4