Console.ReadKey with timeout

There have been multiple times I wished I had a method for this. Often when you are testing things using a plain console application you want to view some output but not have to wait forever (using something like Thread.Sleep) or every time needing to press the ‘Any’ key 😉

Actually I’m a bit surprised .Net hasn’t got something like this built in yet but since it doesn’t I had to create one myself. I created a utility class with a single method to accomplish this. I thought about using an extension method but since the Console class is itself static extension methods does not work for it.

public static class ConsoleHelper
{

public static ConsoleKeyInfo ReadKeyWithTimeOut(int timeOutMS)
{

DateTime timeoutvalue = DateTime.Now.AddMilliseconds(timeOutMS);

while (DateTime.Now < timeoutvalue)
{

if (Console.KeyAvailable)
{

ConsoleKeyInfo cki = Console.ReadKey();
return cki;

}
else
{

System.Threading.Thread.Sleep(100);

}

}
return new ConsoleKeyInfo(‘ ‘, ConsoleKey.Spacebar, false, false, false);

}

}

What this gives you is a method that waits until the specified time-out expires or any (normal) key has been pressed.

  1. Thanks, perfectly working as expected.

  2. Frank Webber

    But is System.Threading.Thread.Sleep(100) not freezing the GUI for the given time?

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>