相关文章推荐
机灵的乌冬面  ·  探索澳门新葡萄新京app官方网站如何带你体验 ...·  1 年前    · 
暗恋学妹的火柴  ·  Web API | Spotify for ...·  1 年前    · 
重情义的吐司  ·  17所!衡水实验中学再获“双一流”高校优秀生 ...·  1 年前    · 
活泼的瀑布  ·  地图显示 - 使用指南 - ...·  1 年前    · 
微笑的冰淇淋  ·  猜字谜:田里种水稻,田外长野草,田上长青草, ...·  2 年前    · 
Code  ›  开发者社区
overflow key
https://cloud.tencent.com/developer/ask/sof/80047
千年单身的蛋挞
3 年前
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
提问
问 如何向Console.ReadLine()添加超时?
Stack Overflow用户
提问于 2008-09-11 20:55:57
EN

我有一个控制台应用程序,我想在其中给用户x秒的时间来响应提示。如果在一段时间后没有输入,程序逻辑应该继续。我们假设超时意味着空响应。

最直接的方法是什么?

24 64.1K 0 票数 131
EN
c#
.net
console
timeout
io

回答 24

Stack Overflow用户

发布于 2010-01-11 19:30:37

string ReadLine(int timeoutms)
    ReadLineDelegate d = Console.ReadLine;
    IAsyncResult result = d.BeginInvoke(null, null);
    result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs
    if (result.IsCompleted)
        string resultstr = d.EndInvoke(result);
        Console.WriteLine("Read: " + resultstr);
        return resultstr;
        Console.WriteLine("Timed out!");
        throw new TimedoutException("Timed Out!");
delegate string ReadLineDelegate();
票数 33
EN

Stack Overflow用户

发布于 2008-09-11 21:06:46

使用 Console.KeyAvailable 的这种方法会有帮助吗?

class Sample 
    public static void Main() 
    ConsoleKeyInfo cki = new ConsoleKeyInfo();
        Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");
// Your code could perform some useful task in the following loop. However, 
// for the sake of this example we'll merely pause for a quarter second.
        while (Console.KeyAvailable == false)
            Thread.Sleep(250); // Loop until input is entered.
        cki = Console.ReadKey(true);
        Console.WriteLine("You pressed the '{0}' key.", cki.Key);
        } while(cki.Key != ConsoleKey.X);
}
票数 28
EN

Stack Overflow用户

发布于 2011-10-06 00:19:50

这对我很有效。

ConsoleKeyInfo k = new ConsoleKeyInfo();
Console.WriteLine("Press any key in the next 5 seconds.");
for (int cnt = 5; cnt > 0; cnt--)
    if (Console.KeyAvailable)
        k = Console.ReadKey();
        break;
 
推荐文章
机灵的乌冬面  ·  探索澳门新葡萄新京app官方网站如何带你体验Grand Lisboa Macau的...
1 年前
暗恋学妹的火柴  ·  Web API | Spotify for Developers
1 年前
重情义的吐司  ·  17所!衡水实验中学再获“双一流”高校优秀生源地授牌!_ 东胜区人民政府网站
1 年前
活泼的瀑布  ·  地图显示 - 使用指南 - JavaScript API GL | 腾讯位置服务
1 年前
微笑的冰淇淋  ·  猜字谜:田里种水稻,田外长野草,田上长青草,细看不是草猜两字-网易公开课
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号