Console.KeyAvailable 启动进程时失败

Console.KeyAvailable Fails When Starting a Process

这是一段运行良好的代码。由于我正在模拟一个很长的 运行ning 过程,所以任何击键都会排队。 Console.Available returns truefalse 正如文档所指示的那样。这里的一切都很好:

while (true) {
   Console.WriteLine("Starting long task...");
   // Simulate some long task by sleeping 3 seconds
   System.Threading.Thread.Sleep(3000);
   Console.WriteLine("Long task is finished.");

   if (Console.KeyAvailable) 
      Console.WriteLine("A key is available: " + Console.ReadKey(false).Key);
   else
      Console.WriteLine("*** No Key available ***");
}

问题是:当我用代码替换 Thread.Sleep() 来创建和 运行 一个真正的 Process 时,Console.KeyAvailable 停止工作。 Console.KeyAvailable 行为不稳定,通常返回 false 但有时会返回 true 如果我足够快地键入足够多的键。

有人对此有解释吗?

while (true) {
   LongRunningProcess("someFile.bin");

   if (Console.KeyAvailable) 
      Console.WriteLine("A key is available: " + Console.ReadKey(false).Key);
   else
      Console.WriteLine("*** No Key available ***");
}

private static bool LongRunningProcess(String filename) {
   ProcessStartInfo processStartInfo = new ProcessStartInfo("BlahBlahBlah.exe", filename);
   processStartInfo.UseShellExecute = false;
   processStartInfo.RedirectStandardError = true;

   Process p = new Process();
   p.StartInfo = processStartInfo;
   p.Start();

   StreamReader stdError = p.StandardError;

   int readResult = stdError.Read();

   p.Close();

   if (readResult != -1) // error was written to std error
      return false;

   return true;
} 

启动的进程显示一个 window 成为活动的 window。当您的控制台 window 处于活动状态 window 时,您的控制台应用程序仅接收键盘输入。尝试将 ProcessStartInfoCreateNoWindow 属性 设置为 true。