首頁 >後端開發 >C++ >如何將超時添加到Console.Readline()?

如何將超時添加到Console.Readline()?

Barbara Streisand
Barbara Streisand原創
2025-01-28 10:51:10982瀏覽

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