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

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

    I struggled with this problem for 5 months before I found an solution that works perfectly in an enterprise setting.

    The problem with most of the solutions so far is that they rely on something other than Console.ReadLine(), and Console.ReadLine() has a lot of advantages:

    • 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).

    My solution is as follows:

    1. Spawn a separate thread to handle the user input using Console.ReadLine().
    2. After the timeout period, unblock Console.ReadLine() by sending an [enter] key into the current console window, using http://inputsimulator.codeplex.com/.

    Sample code:

     InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN);
    

    More information on this technique, including the correct technique to abort a thread that uses Console.ReadLine:

    .NET call to send [enter] keystroke into the current process, which is a console app?

    How to abort another thread in .NET, when said thread is executing Console.ReadLine?

提交回复
热议问题