Console.ReadLine() にタイムアウトを追加するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/57615

質問

ユーザーに提供したいコンソールアプリがあります バツ プロンプトに応答するまでの秒数。一定時間が経過しても入力がなかった場合、プログラムロジックは継続する必要があります。タイムアウトは空の応答を意味すると想定します。

これにアプローチする最も簡単な方法は何ですか?

役に立ちましたか?

解決

5 年経った今でも、すべての回答が次の 1 つ以上の問題を抱えていることを知って驚きました。

  • ReadLine 以外の関数が使用されているため、機能が失われます。(前の入力の場合は、削除/バックスペース/上キー)。
  • 関数を複数回呼び出すと不正な動作が発生します (複数のスレッドが生成されたり、多数の ReadLine がハングしたり、その他の予期しない動作が発生したりします)。
  • 機能はビジーウェイトに依存します。待機は数秒からタイムアウトまで (数分かかる場合もあります) 実行されることが予想されるため、これはひどい無駄です。これほど長時間実行されるビジー待機はリソースを大量に消費し、マルチスレッド シナリオでは特に問題になります。ビジーウェイトがスリープで変更されると、これは応答性に悪影響を及ぼしますが、これはおそらく大きな問題ではないことは認めます。

私の解決策は、上記の問題に悩まされることなく、元の問題を解決すると信じています。

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();
    }
  }

  // omit the parameter to read a line without a timeout
  public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) {
    getInput.Set();
    bool success = gotInput.WaitOne(timeOutMillisecs);
    if (success)
      return input;
    else
      throw new TimeoutException("User did not provide input within the timelimit.");
  }
}

もちろん、電話をかけるのはとても簡単です。

try {
  Console.WriteLine("Please enter your name within the next 5 seconds.");
  string name = Reader.ReadLine(5000);
  Console.WriteLine("Hello, {0}!", name);
} catch (TimeoutException) {
  Console.WriteLine("Sorry, you waited too long.");
}

あるいは、 TryXX(out) シュムエリが示唆したように、慣例としては次のようになります。

  public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) {
    getInput.Set();
    bool success = gotInput.WaitOne(timeOutMillisecs);
    if (success)
      line = input;
    else
      line = null;
    return success;
  }

これは次のように呼ばれます。

Console.WriteLine("Please enter your name within the next 5 seconds.");
string name;
bool success = Reader.TryReadLine(out name, 5000);
if (!success)
  Console.WriteLine("Sorry, you waited too long.");
else
  Console.WriteLine("Hello, {0}!", name);

どちらの場合も、呼び出しを混在させることはできません。 Reader 通常の Console.ReadLine 呼び出し:もし Reader タイムアウトになるとハングアップになります ReadLine 電話。代わりに、通常の(時間制限なし)を使用したい場合は、 ReadLine 電話をかけるだけで、 Reader タイムアウトを省略すると、デフォルトで無限タイムアウトになります。

では、私が言及した他のソリューションの問題についてはどうでしょうか?

  • ご覧のとおり、ReadLine が使用されており、最初の問題が回避されています。
  • この関数は複数回呼び出されても正しく動作します。タイムアウトが発生するかどうかに関係なく、バックグラウンド スレッドは 1 つだけ実行され、ReadLine への呼び出しは最大でも 1 つだけアクティブになります。この関数を呼び出すと、常に最新の入力が得られるか、タイムアウトが発生するため、ユーザーは入力を送信するために Enter キーを複数回押す必要はありません。
  • そして、明らかに、この関数はビジー待機に依存しません。代わりに、適切なマルチスレッド技術を使用してリソースの無駄を防ぎます。

このソリューションで予想される唯一の問題は、スレッドセーフではないことです。ただし、複数のスレッドが同時にユーザーに入力を求めることはできないため、呼び出しを行う前に同期を行う必要があります。 Reader.ReadLine ともかく。

他のヒント

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();

このアプローチは次を使用しますか? Console.KeyAvailable ヘルプ?

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);
    }
}

いずれにせよ、2 番目のスレッドが必要になります。非同期 IO を使用すると、独自の宣言を避けることができます。

  • ManualResetEvent を宣言し、「evt」と呼びます
  • System.Console.OpenStandardInput を呼び出して入力ストリームを取得します。データを保存するコールバック メソッドを指定し、evt を設定します。
  • そのストリームの BeginRead メソッドを呼び出して、非同期読み取り操作を開始します。
  • 次に、ManualResetEvent で時間指定の待機を入力します。
  • 待機がタイムアウトになった場合は、読み取りをキャンセルします

読み取りによってデータが返された場合は、イベントを設定するとメインスレッドが続行されます。それ以外の場合は、タイムアウト後に続行されます。

// Wait for 'Enter' to be pressed or 5 seconds to elapse
using (Stream s = Console.OpenStandardInput())
{
    ManualResetEvent stop_waiting = new ManualResetEvent(false);
    s.BeginRead(new Byte[1], 0, 1, ar => stop_waiting.Set(), null);

    // ...do anything else, or simply...

    stop_waiting.WaitOne(5000);
    // If desired, other threads could also set 'stop_waiting' 
    // Disposing the stream cancels the async read operation. It can be
    // re-opened if needed.
}

これは私にとってはうまくいきました。

ConsoleKeyInfo k = new ConsoleKeyInfo();
Console.WriteLine("Press any key in the next 5 seconds.");
for (int cnt = 5; cnt > 0; cnt--)
  {
    if (Console.KeyAvailable == true)
      {
        k = Console.ReadKey();
        break;
      }
    else
     {
       Console.WriteLine(cnt.ToString());
       System.Threading.Thread.Sleep(1000);
     }
 }
Console.WriteLine("The key pressed was " + k.Key);

セカンダリスレッドを作成して、コンソール上でキーをポーリングする必要があると思います。これを実現する組み込みの方法を私は知りません。

企業環境で完全に機能するソリューションを見つけるまで、私は 5 か月間この問題に取り組みました。

これまでのほとんどのソリューションの問題は、Console.ReadLine() 以外のものに依存していることであり、Console.ReadLine() には多くの利点があります。

  • 削除、バックスペース、矢印キーなどのサポート。
  • 「上」キーを押して最後のコマンドを繰り返す機能 (これは、頻繁に使用されるバックグラウンド デバッグ コンソールを実装する場合に非常に便利です)。

私の解決策は次のとおりです。

  1. スポーンする 別スレッド Console.ReadLine() を使用してユーザー入力を処理します。
  2. タイムアウト期間が経過したら、次のように [enter] キーを現在のコンソール ウィンドウに送信して Console.ReadLine() のブロックを解除します。 http://inputsimulator.codeplex.com/.

サンプルコード:

 InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN);

Console.ReadLine を使用するスレッドを中止する正しい手法など、この手法の詳細については、次を参照してください。

[Enter] キーストロークを現在のプロセス (コンソール アプリ) に送信するための .NET 呼び出し

.NET で別のスレッドが Console.ReadLine を実行しているときに、そのスレッドを中止するにはどうすればよいですか?

デリゲートで Console.ReadLine() を呼び出すと、ユーザーが「Enter」を押さないと呼び出しが返されないため、不適切です。デリゲートを実行しているスレッドは、ユーザーが「Enter」を押すまでブロックされ、キャンセルする方法はありません。

これらの呼び出しを連続して発行すると、期待どおりに動作しません。次のことを考慮してください (上記の Console クラスの例を使用)。

System.Console.WriteLine("Enter your first name [John]:");

string firstName = Console.ReadLine(5, "John");

System.Console.WriteLine("Enter your last name [Doe]:");

string lastName = Console.ReadLine(5, "Doe");

ユーザーは最初のプロンプトでタイムアウトを期限切れにし、2 番目のプロンプトに値を入力します。firstName と lastName の両方にデフォルト値が含まれます。ユーザーが「Enter」を押すと、 初め ReadLine 呼び出しは完了しますが、コードはその呼び出しを放棄し、実質的に結果を破棄します。の 2番 ReadLine 呼び出しは引き続きブロックされ、最終的にタイムアウトが経過し、返される値は再びデフォルトになります。

ところで、上記のコードにはバグがあります。waitHandle.Close() を呼び出すことで、ワーカー スレッドの下からイベントを閉じます。タイムアウトが経過した後にユーザーが「Enter」を押すと、ワーカー スレッドは ObjectDissolvedException をスローするイベントを通知しようとします。例外はワーカー スレッドからスローされ、未処理の例外ハンドラーを設定していない場合、プロセスは終了します。

質問を深読みしすぎているかもしれませんが、キーを押さない限り 15 秒間待機するブート メニューと同様の待ち時間になると思います。(1) ブロッキング関数を使用するか、(2) スレッド、イベント、タイマーを使用することができます。イベントは「続行」として機能し、タイマーが期限切れになるかキーが押されるまでブロックされます。

(1) の疑似コードは次のようになります。

// Get configurable wait time
TimeSpan waitTime = TimeSpan.FromSeconds(15.0);
int configWaitTimeSec;
if (int.TryParse(ConfigManager.AppSetting["DefaultWaitTime"], out configWaitTimeSec))
    waitTime = TimeSpan.FromSeconds(configWaitTimeSec);

bool keyPressed = false;
DateTime expireTime = DateTime.Now + waitTime;

// Timer and key processor
ConsoleKeyInfo cki;
// EDIT: adding a missing ! below
while (!keyPressed && (DateTime.Now < expireTime))
{
    if (Console.KeyAvailable)
    {
        cki = Console.ReadKey(true);
        // TODO: Process key
        keyPressed = true;
    }
    Thread.Sleep(10);
}

あなたがその中にいるなら Main() メソッド、使用できません await, したがって、使用する必要があります Task.WaitAny():

var task = Task.Factory.StartNew(Console.ReadLine);
var result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(5)) == 0
    ? task.Result : string.Empty;

ただし、C# 7.1 では、非同期を作成する機能が導入されています。 Main() メソッドを使用することをお勧めします。 Task.WhenAny() そのオプションがある場合は常にバージョンを指定します。

var task = Task.Factory.StartNew(Console.ReadLine);
var completedTask = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5)));
var result = object.ReferenceEquals(task, completedTask) ? task.Result : string.Empty;

残念ながら Gulzar の投稿にはコメントできませんが、より詳しい例を次に示します。

            while (Console.KeyAvailable == false)
            {
                Thread.Sleep(250);
                i++;
                if (i > 3)
                    throw new Exception("Timedout waiting for input.");
            }
            input = Console.ReadLine();

編集:実際の作業を別のプロセスで実行し、タイムアウトになった場合にそのプロセスを強制終了することで問題を修正しました。詳細については以下を参照してください。ふぅ!

これを実行してみたところ、うまく機能しているようでした。私の同僚は Thread オブジェクトを使用するバージョンを持っていましたが、私はデリゲート型の BeginInvoke() メソッドの方がもう少しエレガントだと思います。

namespace TimedReadLine
{
   public static class Console
   {
      private delegate string ReadLineInvoker();

      public static string ReadLine(int timeout)
      {
         return ReadLine(timeout, null);
      }

      public static string ReadLine(int timeout, string @default)
      {
         using (var process = new System.Diagnostics.Process
         {
            StartInfo =
            {
               FileName = "ReadLine.exe",
               RedirectStandardOutput = true,
               UseShellExecute = false
            }
         })
         {
            process.Start();

            var rli = new ReadLineInvoker(process.StandardOutput.ReadLine);
            var iar = rli.BeginInvoke(null, null);

            if (!iar.AsyncWaitHandle.WaitOne(new System.TimeSpan(0, 0, timeout)))
            {
               process.Kill();
               return @default;
            }

            return rli.EndInvoke(iar);
         }
      }
   }
}

ReadLine.exe プロジェクトは、次のような 1 つのクラスを持つ非常に単純なプロジェクトです。

namespace ReadLine
{
   internal static class Program
   {
      private static void Main()
      {
         System.Console.WriteLine(System.Console.ReadLine());
      }
   }
}

.NET 4 では、タスクを使用することでこれが驚くほど簡単になります。

まず、ヘルパーを構築します。

   Private Function AskUser() As String
      Console.Write("Answer my question: ")
      Return Console.ReadLine()
   End Function

次に、タスクを実行して待機します。

      Dim askTask As Task(Of String) = New TaskFactory().StartNew(Function() AskUser())
      askTask.Wait(TimeSpan.FromSeconds(30))
      If Not askTask.IsCompleted Then
         Console.WriteLine("User failed to respond.")
      Else
         Console.WriteLine(String.Format("You responded, '{0}'.", askTask.Result))
      End If

これを機能させるために ReadLine 機能を再作成したり、他の危険なハックを実行したりする必要はありません。タスクを使用すると、非常に自然な方法で質問を解決できます。

ここにまだ十分な答えがないかのように:0)、以下は上記の静的メソッド @kwl のソリューション (最初のもの) にカプセル化されます。

    public static string ConsoleReadLineWithTimeout(TimeSpan timeout)
    {
        Task<string> task = Task.Factory.StartNew(Console.ReadLine);

        string result = Task.WaitAny(new Task[] { task }, timeout) == 0
            ? task.Result 
            : string.Empty;
        return result;
    }

使用法

    static void Main()
    {
        Console.WriteLine("howdy");
        string result = ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(8.5));
        Console.WriteLine("bye");
    }

これを解決する簡単なスレッド例

Thread readKeyThread = new Thread(ReadKeyMethod);
static ConsoleKeyInfo cki = null;

void Main()
{
    readKeyThread.Start();
    bool keyEntered = false;
    for(int ii = 0; ii < 10; ii++)
    {
        Thread.Sleep(1000);
        if(readKeyThread.ThreadState == ThreadState.Stopped)
            keyEntered = true;
    }
    if(keyEntered)
    { //do your stuff for a key entered
    }
}

void ReadKeyMethod()
{
    cki = Console.ReadKey();
}

または、行全体を取得するために上部の静的文字列を使用します。

私の場合、これはうまくいきます:

public static ManualResetEvent evtToWait = new ManualResetEvent(false);

private static void ReadDataFromConsole( object state )
{
    Console.WriteLine("Enter \"x\" to exit or wait for 5 seconds.");

    while (Console.ReadKey().KeyChar != 'x')
    {
        Console.Out.WriteLine("");
        Console.Out.WriteLine("Enter again!");
    }

    evtToWait.Set();
}

static void Main(string[] args)
{
        Thread status = new Thread(ReadDataFromConsole);
        status.Start();

        evtToWait = new ManualResetEvent(false);

        evtToWait.WaitOne(5000); // wait for evtToWait.Set() or timeOut

        status.Abort(); // exit anyway
        return;
}

これって短くて素敵じゃないですか?

if (SpinWait.SpinUntil(() => Console.KeyAvailable, millisecondsTimeout))
{
    ConsoleKeyInfo keyInfo = Console.ReadKey();

    // Handle keyInfo value here...
}

これは、Glen Slayden のソリューションの完全な例です。別の問題のテストケースを構築するときに、たまたまこれを作成しました。非同期 I/O と手動リセット イベントを使用します。

public static void Main() {
    bool readInProgress = false;
    System.IAsyncResult result = null;
    var stop_waiting = new System.Threading.ManualResetEvent(false);
    byte[] buffer = new byte[256];
    var s = System.Console.OpenStandardInput();
    while (true) {
        if (!readInProgress) {
            readInProgress = true;
            result = s.BeginRead(buffer, 0, buffer.Length
              , ar => stop_waiting.Set(), null);

        }
        bool signaled = true;
        if (!result.IsCompleted) {
            stop_waiting.Reset();
            signaled = stop_waiting.WaitOne(5000);
        }
        else {
            signaled = true;
        }
        if (signaled) {
            readInProgress = false;
            int numBytes = s.EndRead(result);
            string text = System.Text.Encoding.UTF8.GetString(buffer
              , 0, numBytes);
            System.Console.Out.Write(string.Format(
              "Thank you for typing: {0}", text));
        }
        else {
            System.Console.Out.WriteLine("oy, type something!");
        }
    }

2 番目のスレッドを取得するもう 1 つの安価な方法は、それをデリゲートでラップすることです。

上記の Eric の投稿の実装例。この特定の例は、パイプ経由でコンソール アプリに渡された情報を読み取るために使用されました。

 using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace PipedInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader buffer = ReadPipedInfo();

            Console.WriteLine(buffer.ReadToEnd());
        }

        #region ReadPipedInfo
        public static StreamReader ReadPipedInfo()
        {
            //call with a default value of 5 milliseconds
            return ReadPipedInfo(5);
        }

        public static StreamReader ReadPipedInfo(int waitTimeInMilliseconds)
        {
            //allocate the class we're going to callback to
            ReadPipedInfoCallback callbackClass = new ReadPipedInfoCallback();

            //to indicate read complete or timeout
            AutoResetEvent readCompleteEvent = new AutoResetEvent(false);

            //open the StdIn so that we can read against it asynchronously
            Stream stdIn = Console.OpenStandardInput();

            //allocate a one-byte buffer, we're going to read off the stream one byte at a time
            byte[] singleByteBuffer = new byte[1];

            //allocate a list of an arbitary size to store the read bytes
            List<byte> byteStorage = new List<byte>(4096);

            IAsyncResult asyncRead = null;
            int readLength = 0; //the bytes we have successfully read

            do
            {
                //perform the read and wait until it finishes, unless it's already finished
                asyncRead = stdIn.BeginRead(singleByteBuffer, 0, singleByteBuffer.Length, new AsyncCallback(callbackClass.ReadCallback), readCompleteEvent);
                if (!asyncRead.CompletedSynchronously)
                    readCompleteEvent.WaitOne(waitTimeInMilliseconds);

                //end the async call, one way or another

                //if our read succeeded we store the byte we read
                if (asyncRead.IsCompleted)
                {
                    readLength = stdIn.EndRead(asyncRead);
                    if (readLength > 0)
                        byteStorage.Add(singleByteBuffer[0]);
                }

            } while (asyncRead.IsCompleted && readLength > 0);
            //we keep reading until we fail or read nothing

            //return results, if we read zero bytes the buffer will return empty
            return new StreamReader(new MemoryStream(byteStorage.ToArray(), 0, byteStorage.Count));
        }

        private class ReadPipedInfoCallback
        {
            public void ReadCallback(IAsyncResult asyncResult)
            {
                //pull the user-defined variable and strobe the event, the read finished successfully
                AutoResetEvent readCompleteEvent = asyncResult.AsyncState as AutoResetEvent;
                readCompleteEvent.Set();
            }
        }
        #endregion ReadPipedInfo
    }
}
string readline = "?";
ThreadPool.QueueUserWorkItem(
    delegate
    {
        readline = Console.ReadLine();
    }
);
do
{
    Thread.Sleep(100);
} while (readline == "?");

「Console.ReadKey」ルートをたどると、ReadLine の優れた機能の一部が失われることに注意してください。

  • 削除、バックスペース、矢印キーなどのサポート。
  • 「上」キーを押して最後のコマンドを繰り返す機能 (これは、頻繁に使用されるバックグラウンド デバッグ コンソールを実装する場合に非常に便利です)。

タイムアウトを追加するには、それに合わせて while ループを変更します。

既存の大量の回答に別のソリューションを追加した私を嫌いにならないでください。これは Console.ReadKey() で機能しますが、ReadLine() などで機能するように簡単に変更できます。

「Console.Read」メソッドがブロックしているため、「ナッジ" 読み取りをキャンセルするための StdIn ストリーム。

呼び出し構文:

ConsoleKeyInfo keyInfo;
bool keyPressed = AsyncConsole.ReadKey(500, out keyInfo);
// where 500 is the timeout

コード:

public class AsyncConsole // not thread safe
{
    private static readonly Lazy<AsyncConsole> Instance =
        new Lazy<AsyncConsole>();

    private bool _keyPressed;
    private ConsoleKeyInfo _keyInfo;

    private bool DoReadKey(
        int millisecondsTimeout,
        out ConsoleKeyInfo keyInfo)
    {
        _keyPressed = false;
        _keyInfo = new ConsoleKeyInfo();

        Thread readKeyThread = new Thread(ReadKeyThread);
        readKeyThread.IsBackground = false;
        readKeyThread.Start();

        Thread.Sleep(millisecondsTimeout);

        if (readKeyThread.IsAlive)
        {
            try
            {
                IntPtr stdin = GetStdHandle(StdHandle.StdIn);
                CloseHandle(stdin);
                readKeyThread.Join();
            }
            catch { }
        }

        readKeyThread = null;

        keyInfo = _keyInfo;
        return _keyPressed;
    }

    private void ReadKeyThread()
    {
        try
        {
            _keyInfo = Console.ReadKey();
            _keyPressed = true;
        }
        catch (InvalidOperationException) { }
    }

    public static bool ReadKey(
        int millisecondsTimeout,
        out ConsoleKeyInfo keyInfo)
    {
        return Instance.Value.DoReadKey(millisecondsTimeout, out keyInfo);
    }

    private enum StdHandle { StdIn = -10, StdOut = -11, StdErr = -12 };

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetStdHandle(StdHandle std);

    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(IntPtr hdl);
}

これを使用する解決策は次のとおりです Console.KeyAvailable. 。これらはブロック呼び出しですが、必要に応じて TPL 経由で非同期に呼び出すことは非常に簡単です。標準のキャンセル メカニズムを使用して、タスク非同期パターンなどの優れた機能を簡単に接続できるようにしました。

public static class ConsoleEx
{
  public static string ReadLine(TimeSpan timeout)
  {
    var cts = new CancellationTokenSource();
    return ReadLine(timeout, cts.Token);
  }

  public static string ReadLine(TimeSpan timeout, CancellationToken cancellation)
  {
    string line = "";
    DateTime latest = DateTime.UtcNow.Add(timeout);
    do
    {
        cancellation.ThrowIfCancellationRequested();
        if (Console.KeyAvailable)
        {
            ConsoleKeyInfo cki = Console.ReadKey();
            if (cki.Key == ConsoleKey.Enter)
            {
                return line;
            }
            else
            {
                line += cki.KeyChar;
            }
        }
        Thread.Sleep(1);
    }
    while (DateTime.UtcNow < latest);
    return null;
  }
}

これにはいくつかの欠点があります。

  • 標準のナビゲーション機能は利用できません。 ReadLine (上下矢印スクロールなど) を提供します。
  • これにより、特殊キー (F1、PrtScn など) が押された場合に、入力に「\0」文字が挿入されます。ただし、コードを変更することで簡単にそれらを除外できます。

重複した質問があったため、ここにたどり着きました。私は簡単に見える次の解決策を思いつきました。私が見逃していたいくつかの欠点があると確信しています。

static void Main(string[] args)
{
    Console.WriteLine("Hit q to continue or wait 10 seconds.");

    Task task = Task.Factory.StartNew(() => loop());

    Console.WriteLine("Started waiting");
    task.Wait(10000);
    Console.WriteLine("Stopped waiting");
}

static void loop()
{
    while (true)
    {
        if ('q' == Console.ReadKey().KeyChar) break;
    }
}

私はこの答えに到達し、最終的に次のことを行いました。

    /// <summary>
    /// Reads Line from console with timeout. 
    /// </summary>
    /// <exception cref="System.TimeoutException">If user does not enter line in the specified time.</exception>
    /// <param name="timeout">Time to wait in milliseconds. Negative value will wait forever.</param>        
    /// <returns></returns>        
    public static string ReadLine(int timeout = -1)
    {
        ConsoleKeyInfo cki = new ConsoleKeyInfo();
        StringBuilder sb = new StringBuilder();

        // if user does not want to spesify a timeout
        if (timeout < 0)
            return Console.ReadLine();

        int counter = 0;

        while (true)
        {
            while (Console.KeyAvailable == false)
            {
                counter++;
                Thread.Sleep(1);
                if (counter > timeout)
                    throw new System.TimeoutException("Line was not entered in timeout specified");
            }

            cki = Console.ReadKey(false);

            if (cki.Key == ConsoleKey.Enter)
            {
                Console.WriteLine();
                return sb.ToString();
            }
            else
                sb.Append(cki.KeyChar);                
        }            
    }

を使用した簡単な例 Console.KeyAvailable:

Console.WriteLine("Press any key during the next 2 seconds...");
Thread.Sleep(2000);
if (Console.KeyAvailable)
{
    Console.WriteLine("Key pressed");
}
else
{
    Console.WriteLine("You were too slow");
}

より現代的なタスクベースのコードは次のようになります。

public string ReadLine(int timeOutMillisecs)
{
    var inputBuilder = new StringBuilder();

    var task = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            var consoleKey = Console.ReadKey(true);
            if (consoleKey.Key == ConsoleKey.Enter)
            {
                return inputBuilder.ToString();
            }

            inputBuilder.Append(consoleKey.KeyChar);
        }
    });


    var success = task.Wait(timeOutMillisecs);
    if (!success)
    {
        throw new TimeoutException("User did not provide input within the timelimit.");
    }

    return inputBuilder.ToString();
}

Windows アプリケーション (Windows サービス) があるという特殊な状況がありました。プログラムを対話的に実行する場合 Environment.IsInteractive (VS デバッガーまたは cmd.exe から)、AttachConsole/AllocConsole を使用して stdin/stdout を取得しました。作業の実行中にプロセスが終了しないようにするために、UI スレッドは呼び出します。 Console.ReadKey(false). 。UIスレッドが別のスレッドから実行している待機をキャンセルしたかったので、@JSquaredDによる解決策の変更を思いつきました。

using System;
using System.Diagnostics;

internal class PressAnyKey
{
  private static Thread inputThread;
  private static AutoResetEvent getInput;
  private static AutoResetEvent gotInput;
  private static CancellationTokenSource cancellationtoken;

  static PressAnyKey()
  {
    // Static Constructor called when WaitOne is called (technically Cancel too, but who cares)
    getInput = new AutoResetEvent(false);
    gotInput = new AutoResetEvent(false);
    inputThread = new Thread(ReaderThread);
    inputThread.IsBackground = true;
    inputThread.Name = "PressAnyKey";
    inputThread.Start();
  }

  private static void ReaderThread()
  {
    while (true)
    {
      // ReaderThread waits until PressAnyKey is called
      getInput.WaitOne();
      // Get here 
      // Inner loop used when a caller uses PressAnyKey
      while (!Console.KeyAvailable && !cancellationtoken.IsCancellationRequested)
      {
        Thread.Sleep(50);
      }
      // Release the thread that called PressAnyKey
      gotInput.Set();
    }
  }

  /// <summary>
  /// Signals the thread that called WaitOne should be allowed to continue
  /// </summary>
  public static void Cancel()
  {
    // Trigger the alternate ending condition to the inner loop in ReaderThread
    if(cancellationtoken== null) throw new InvalidOperationException("Must call WaitOne before Cancelling");
    cancellationtoken.Cancel();
  }

  /// <summary>
  /// Wait until a key is pressed or <see cref="Cancel"/> is called by another thread
  /// </summary>
  public static void WaitOne()
  {
    if(cancellationtoken==null || cancellationtoken.IsCancellationRequested) throw new InvalidOperationException("Must cancel a pending wait");
    cancellationtoken = new CancellationTokenSource();
    // Release the reader thread
    getInput.Set();
    // Calling thread will wait here indefiniately 
    // until a key is pressed, or Cancel is called
    gotInput.WaitOne();
  }    
}

これは、ネイティブ API を使用しない、最も単純で実用的なソリューションのようです。

    static Task<string> ReadLineAsync(CancellationToken cancellation)
    {
        return Task.Run(() =>
        {
            while (!Console.KeyAvailable)
            {
                if (cancellation.IsCancellationRequested)
                    return null;

                Thread.Sleep(100);
            }
            return Console.ReadLine();
        });
    }

使用例:

    static void Main(string[] args)
    {
        AsyncContext.Run(async () =>
        {
            CancellationTokenSource cancelSource = new CancellationTokenSource();
            cancelSource.CancelAfter(1000);
            Console.WriteLine(await ReadLineAsync(cancelSource.Token) ?? "null");
        });
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top