【发布时间】:2016-10-20 22:25:33
【问题描述】:
这是一个运行良好的代码的 sn-p。当我模拟一个长时间运行的过程时,任何击键都会排队。 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 ***");
}
问题是:当我用代码替换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;
}
【问题讨论】:
标签: c# .net console-application system.diagnostics