为 Console.ReadLine()
添加超时机制
控制台应用程序需要用户输入才能运行,但如果用户响应时间过长会发生什么?实现超时机制允许您的程序即使用户未在指定时间内提供输入也能继续执行。
最直接的方法是使用带有计时器的 while 循环来定期检查输入。如果在没有输入的情况下经过一定的时间,程序可以抛出超时异常。
<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>
对于更高级的超时机制,可以使用多线程方法。后台线程监听输入,而主线程暂停执行。收到输入后,后台线程发出信号,让主线程继续执行。
<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>
这两个例子都展示了如何为 Console.ReadLine()
添加超时功能,第一个例子更简洁,第二个例子更健壮,适用于更复杂的场景。 选择哪个方法取决于你的具体需求和对代码复杂度的容忍度。
以上是如何实现Console.Readline()的超时?的详细内容。更多信息请关注PHP中文网其他相关文章!