首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何向Console.ReadLine()添加超时?

如何向Console.ReadLine()添加超时?
EN

Stack Overflow用户
提问于 2008-09-11 20:55:57
回答 24查看 64.1K关注 0票数 131

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

最直接的方法是什么?

EN

回答 24

Stack Overflow用户

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

代码语言:javascript
复制
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;
    }
    else
    {
        Console.WriteLine("Timed out!");
        throw new TimedoutException("Timed Out!");
    }
}

delegate string ReadLineDelegate();
票数 33
EN

Stack Overflow用户

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

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

代码语言:javascript
复制
class Sample 
{
    public static void Main() 
    {
    ConsoleKeyInfo cki = new ConsoleKeyInfo();

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

这对我很有效。

代码语言:javascript
复制
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;
      }
    else
     {
       Console.WriteLine(cnt.ToString());
       System.Threading.Thread.Sleep(1000);
     }
 }
Console.WriteLine("The key pressed was " + k.Key);
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57615

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档