c# ProcessStartInfo.Start - reading output but with a timeout

后端 未结 6 1534
小鲜肉
小鲜肉 2020-12-08 23:53

If you want to start another process and wait (with time out) to finish you can use the following (from MSDN).

//Set a time-out value.
int timeOut=5000;
//Ge         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 00:49

    This technique will hang if the output buffer is filled with more that 4KB of data. A more foolproof method is to register delegates to be notified when something is written to the output stream. I've already suggested this method before in another post:

    ProcessStartInfo processInfo = new ProcessStartInfo("Write500Lines.exe");
    processInfo.ErrorDialog = false;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardOutput = true;
    processInfo.RedirectStandardError = true;
    
    Process proc = Process.Start(processInfo);
    
    // You can pass any delegate that matches the appropriate 
    // signature to ErrorDataReceived and OutputDataReceived
    proc.ErrorDataReceived += (sender, errorLine) => { if (errorLine.Data != null) Trace.WriteLine(errorLine.Data); };
    proc.OutputDataReceived += (sender, outputLine) => { if (outputLine.Data != null) Trace.WriteLine(outputLine.Data); };
    proc.BeginErrorReadLine();
    proc.BeginOutputReadLine();
    
    proc.WaitForExit();
    

提交回复
热议问题