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

后端 未结 30 2564
耶瑟儿~
耶瑟儿~ 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:45

    string readline = "?";
    ThreadPool.QueueUserWorkItem(
        delegate
        {
            readline = Console.ReadLine();
        }
    );
    do
    {
        Thread.Sleep(100);
    } while (readline == "?");
    

    Note that if you go down the "Console.ReadKey" route, you lose some of the cool features of ReadLine, namely:

    • Support for delete, backspace, arrow keys, etc.
    • The ability to press the "up" key and repeat the last command (this comes in very handy if you implement a background debugging console that gets a lot of use).

    To add a timeout, alter the while loop to suit.

提交回复
热议问题