Enter the timeout mechanism to enter the console
Console applications often use
methods to indicate the user input. However, especially in automation scenarios, it may be necessary to restrict user response time. This leads to a question: How do we deal with this situation to add timeout mechanism? Console.ReadLine()
Console.ReadLine()
The complete solution
Although there may be some limitations in the previous solutions, such as relying on alternative functions, abnormal behavior or resource -intensive waiting when multiple calls, this advanced solution effectively solves these problems:
The advantages of this solution
<code class="language-csharp">class Reader { private static Thread inputThread; private static AutoResetEvent getInput, gotInput; private static string input; static Reader() { getInput = new AutoResetEvent(false); gotInput = new AutoResetEvent(false); inputThread = new Thread(reader); inputThread.IsBackground = true; inputThread.Start(); } private static void reader() { while (true) { getInput.WaitOne(); input = Console.ReadLine(); gotInput.Set(); } } public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) return input; else throw new TimeoutException("用户未在规定时间内提供输入。"); } public static bool TryReadLine(out string result, int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) { result = input; return true; } else { result = null; return false; } } }</code>
Reserve function: Different from other methods. This solution uses
to retain all its functions, including the editor.Console.ReadLine()
Eliminate busy waiting: method with output parameters:
Conclusion
<code class="language-csharp">try { Console.WriteLine("请在接下来的 5 秒内输入您的姓名。"); string name = Reader.ReadLine(5000); Console.WriteLine("您好,{0}!", name); } catch (TimeoutException) { Console.WriteLine("抱歉,您等待的时间过长。"); }</code>
to effectively handle the user input scenarios with a specified time limit. TryReadLine
The above is the detailed content of How Can I Add a Timeout to Console.ReadLine()?. For more information, please follow other related articles on the PHP Chinese website!