10

I have built a simple console application, and I need to give a specific time for user to input a keychar.

Should I use this?

System.Threading.Thread.Sleep(1000);

For those who didn't understand, I need the program to skip the Console.ReadKey().KeyChar; after x seconds.

Is this possible?

Anthony
  • 12,177
  • 9
  • 69
  • 105
user3107990
  • 147
  • 1
  • 10

2 Answers2

22

I would do it like this:

DateTime beginWait = DateTime.Now;
while (!Console.KeyAvailable && DateTime.Now.Subtract(beginWait).TotalSeconds < 5)
    Thread.Sleep(250);

if (!Console.KeyAvailable)
    Console.WriteLine("You didn't press anything!");
else
    Console.WriteLine("You pressed: {0}", Console.ReadKey().KeyChar);
Tony
  • 7,345
  • 3
  • 26
  • 34
0

Problem : if you use Thread.Sleep() to wait for 1 second it hangs the Main Thread for given period of time.

Solution : you can use System.Timers.Timer to wait for given amount of time.

Try This:

    System.Timers.Timer timer1 = new System.Timers.Timer();
    timer1.Interval=1000;//one second
    timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
    timer1.Start();
    char ch;
    private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        ch=Console.ReadKey().KeyChar;
        //stop the timer whenever needed
        //timer1.Stop();
    }
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
  • this is not what OP needed, in your solution you call `Console.ReadKey()` periodically, but OP want **skip** _the Console.ReadKey().KeyChar; after x seconds_ – Grundy Dec 17 '13 at 07:50
  • @Grundy: this is not exact solution, as OP just asked `Should I use this? Thread.Sleep()` it answers the question IMO. i would have provided exact solution if he has shown his code. – Sudhakar Tillapudi Dec 17 '13 at 07:52
  • 1
    OP asked about using it for concrete problem, but in your answer something else – Grundy Dec 17 '13 at 07:59