C# 启动进程时Console.KeyAvailable失败

C# 启动进程时Console.KeyAvailable失败,c#,.net,console-application,system.diagnostics,C#,.net,Console Application,System.diagnostics,下面是一段代码,它工作得很好。当我模拟一个长时间运行的进程时,任何击键都会排队。Console.Available返回true和false,正如文档所示。这里一切都很好: while (true) { Console.WriteLine("Starting long task..."); // Simulate some long task by sleeping 3 seconds System.Threading.Thread.Sleep(3000); Console

下面是一段代码,它工作得很好。当我模拟一个长时间运行的进程时,任何击键都会排队。
Console.Available
返回
true
false
,正如文档所示。这里一切都很好:

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

问题是:当我用代码替换
线程.Sleep()
来创建并运行真正的
进程时,
控制台.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;
} 

启动的进程将显示一个窗口,该窗口将变为活动窗口。当控制台窗口是活动窗口时,控制台应用程序仅接收键盘输入。尝试将
ProcessStartInfo
CreateNoWindow
属性设置为true