在c#中不断读取控制台流
我想在c#中读取cmd的连续输出流。 我知道我可以重定向标准输出流并读取它。 以下是代码:
System.Diagnostics.ProcessStartInfo pi= new System.Diagnostics.ProcessStartInfo(ProgramPATH,Params); pi.RedirectStandardOutput = true; pi.UseShellExecute = false; pi.CreateNoWindow = true; System.Diagnostics.Process proc= new System.Diagnostics.Process(); proc.StartInfo = pi; proc.Start(); string result = proc.StandardOutput.ReadToEnd();
但这会立即产生整个输出。 如果我用-t
参数发出ping
命令怎么办? 我如何不断阅读这个流?
你正在调用ReadToEnd
,它会明显阻塞,直到进程终止。 您可以反复调用Read
或ReadLine
。 但是,您应该考虑在不同的线程中执行此操作, 或者使用诸如OutputDataReceived
事件来执行此操作。 (如果您正在使用事件,则需要调用BeginOutputReadLine
来启用事件 – 有关详细信息,请参阅MSDN示例。)
可能在不同线程上读取的原因是,如果需要读取标准错误和标准输出,则需要确保进程没有填满其缓冲区 – 否则可能会在写入时阻塞,从而导致死锁。 使用异步方法可以更轻松地处理这个问题。