Skip to main content
 首页 » 编程设计

c#之ReadToEnd 来自进程的标准输出和 waitforexit

2024年02月20日14think

来自 MSDN 使用新创建进程的 stdoutput 的例子:

    // 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(); 

如果我使用的不是 myStreamReader.ReadLine(),而是 myStreamReader.ReadToEnd(),我是否仍应使用 myProcess.WaitForExit()? 还是 ReadToEnd() 会等到进程结束?

请您参考如下方法:

编辑: 很抱歉打扰,直接回答你的问题。是的,您需要调用 Process.WaitForExit();。这将确保在您调用 ReadToEnd()

之前,进程已产生 所有输出

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

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