How to add a Timeout to Console.ReadLine()?

后端 未结 30 2555
耶瑟儿~
耶瑟儿~ 2020-11-22 04:57

I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 05:35

    EDIT: fixed the problem by having the actual work be done in a separate process and killing that process if it times out. See below for details. Whew!

    Just gave this a run and it seemed to work nicely. My coworker had a version which used a Thread object, but I find the BeginInvoke() method of delegate types to be a bit more elegant.

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

    The ReadLine.exe project is a very simple one which has one class which looks like so:

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

提交回复
热议问题