adding a timeout mechanism
Console.ReadLine()
The console application requires the user input to run, but what will happen if the user responds too long? Implementing the time -out mechanism allows your program to continue to execute even if the user does not provide input within the specified time.
Implementation method
The most direct method is to use the WHILE cycle with a timer to check the input regularly. If it takes a certain time without input, the program can throw out the timeout.The advanced method of using AutoreSetevent
<code class="language-csharp">using System; using System.Threading; public class ConsoleTimeout { public static string InputWithTimeout(int timeoutSeconds) { Console.WriteLine("请输入内容:"); var timer = new Timer((_) => { throw new TimeoutException("输入超时"); }, null, timeoutSeconds * 1000, Timeout.Infinite); string input = Console.ReadLine(); timer.Dispose(); return input; } }</code>
These two examples show how to add timeout functions to
. The first example is more concise, the second example is more robust, and it is suitable for more complicated scenes. Which method to choose depends on your specific needs and tolerance for code complexity.<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("用户未在规定时间内提供输入。"); } }</code>
The above is the detailed content of How to Implement a Timeout for Console.ReadLine()?. For more information, please follow other related articles on the PHP Chinese website!