1

From the MSDN example of using stdoutput of newly created process:

    // This is the code for the base process
    Process myProcess = new Process();
    // Start a new instance of this program but specify the 'spawned' version.
    ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(args[0], "spawn");
    myProcessStartInfo.UseShellExecute = false;
    myProcessStartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo = myProcessStartInfo;
    myProcess.Start();
    StreamReader myStreamReader = myProcess.StandardOutput;
    // Read the standard output of the spawned process. 
    string myString = myStreamReader.ReadLine();
    Console.WriteLine(myString);
    myProcess.WaitForExit();
    myProcess.Close();

If instead of myStreamReader.ReadLine() I'm using myStreamReader.ReadToEnd() shall I still use myProcess.WaitForExit()? Or ReadToEnd() will wait until the process is finished?

4

2 回答 2

3

编辑: 对不起转移,直接回答你的问题。是的,你需要打电话Process.WaitForExit();。这将确保该过程在您调用之前已经产生了所有输出ReadToEnd()

ReadToEnd 是同步函数。因此,如果您不在代码中调用它,它将阻塞您的主线程,直到它仅捕获 StandardOutput 的第一个输出,然后就是这样。但是使用 WaitForExit 将确保您拥有一切。

您也可以考虑对进程的输出进行异步读取,请参阅实现的这个MSDN 示例OutputDataRecieved

于 2012-09-10T20:17:56.100 回答
1

“ReadToEnd”是一个存储在“StreamReader”对象中的函数,我认为它与等待进程退出无关,但是“Process”类可能会自行处理。顺便说一句,“StreamReader”的所有能力在你提到的情况下都没有用。

在我看来,应该调用“WaitForExit”,就像你也应该调用“Close”一样。因为它们会释放一些其他方法无法释放的系统资源。据我所知,“ReadToEnd”方法与调用这两个方法无关。

干杯

于 2012-09-10T19:29:22.187 回答