首页 >后端开发 >C++ >如何将超时添加到Console.Readline()?

如何将超时添加到Console.Readline()?

Barbara Streisand
Barbara Streisand原创
2025-01-28 10:51:10959浏览

How Can I Add a Timeout to Console.ReadLine()?

为控制台输入添加超时机制

问题描述

控制台应用程序经常使用 Console.ReadLine() 方法提示用户输入。但是,尤其是在自动化场景中,限制用户响应时间可能很有必要。这就引出了一个问题:我们如何为 Console.ReadLine() 添加超时机制来处理这种情况?

完整的解决方案

虽然之前的解决方案可能存在一些局限性,例如依赖于替代函数、多次调用时行为异常或资源密集型忙等待,但此高级解决方案有效地解决了这些问题:

<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>

此解决方案的优势

  • 保留功能: 与其他方法不同,此解决方案使用 Console.ReadLine(),保留其全部功能,包括行编辑。
  • 管理多次调用: 它确保连续调用能够正常运行,不会产生多个线程或死锁。
  • 消除忙等待: 该解决方案采用多线程来避免浪费与忙等待相关的资源。

示例用法

为了说明其用法,请考虑以下示例:

<code class="language-csharp">try
{
    Console.WriteLine("请在接下来的 5 秒内输入您的姓名。");
    string name = Reader.ReadLine(5000);
    Console.WriteLine("您好,{0}!", name);
}
catch (TimeoutException)
{
    Console.WriteLine("抱歉,您等待的时间过长。");
}</code>

或者,您可以使用带输出参数的 TryReadLine 方法:

<code class="language-csharp">Console.WriteLine("请在接下来的 5 秒内输入您的姓名。");
string name;
bool success = Reader.TryReadLine(out name, 5000);
if (!success)
    Console.WriteLine("抱歉,您等待的时间过长。");
else
    Console.WriteLine("您好,{0}!", name);</code>

结论

此高级解决方案提供了一种全面且高效的方法来为 Console.ReadLine() 添加超时机制,有效地处理具有指定时间限制的用户输入场景。

以上是如何将超时添加到Console.Readline()?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn