1

如果我有诸如

proc.Start();
string resultOut;

while ( (!proc.HasExited && (resultOut = stdOut.ReadLine()) != null))
{
// Do some operation based on resultOut
}

从我开始 proc 到捕获/解析开始时,我是否可能会错过一些行,还是会等待?如果没有,我该怎么办?

4

2 回答 2

2

如果您通过ProcessStartInfo.RedirectStandardOutput等重定向流程的输入和/或输出,则流程输出将直接进入您的流。您不会错过任何输入或输出。

于 2010-09-10T20:23:33.540 回答
2

以下代码不会丢失标准输出中的任何行。

var startInfo = new ProcessStartInfo
{
    FileName = "my.exe",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

using (var process = new Process { StartInfo = startInfo })
{
    process.ErrorDataReceived += (s, e) =>
    {
        string line = e.Data;            
        //process stderr lines

    };

    process.OutputDataReceived += (s, e) =>
    {
        string line = e.Data;
        //process stdout lines
    };

    process.Start();

    process.BeginErrorReadLine();
    process.BeginOutputReadLine();

    process.WaitForExit();
}
于 2010-09-10T23:10:44.613 回答