How to add a Timeout to Console.ReadLine()?

后端 未结 30 2927
耶瑟儿~
耶瑟儿~ 2020-11-22 04:57

I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should

30条回答
  •  执笔经年
    2020-11-22 05:43

    A simple example using Console.KeyAvailable:

    Console.WriteLine("Press any key during the next 2 seconds...");
    Thread.Sleep(2000);
    if (Console.KeyAvailable)
    {
        Console.WriteLine("Key pressed");
    }
    else
    {
        Console.WriteLine("You were too slow");
    }
    

提交回复
热议问题