首页 > 后端开发 > C++ > 如何实现Console.Readline()的超时?

如何实现Console.Readline()的超时?

Barbara Streisand
发布: 2025-01-28 10:36:10
原创
677 人浏览过

How to Implement a Timeout for Console.ReadLine()?

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>
登录后复制

使用 AutoResetEvent 的高级方法

对于更高级的超时机制,可以使用多线程方法。后台线程监听输入,而主线程暂停执行。收到输入后,后台线程发出信号,让主线程继续执行。

<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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板