Вот фрагмент кода, который работает отлично. Поскольку я имитирую длительный процесс, любые нажатия клавиш помещаются в очередь. Console.Available
возвращает true
и false
, как указано в документации. Все прекрасно работает здесь:Console.KeyAvailable Fails при запуске процесса
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;
}