solve the problem of processtartinfo.waitForexit () blocking problem: asynchronous reading method
In some cases, when using
, the program will hang out indefinitely at. This problem occurs when the standard output buffer reaches its limit. The problem of redirection to the standard output and standard errors increases this problem, which leads to a deadlock. ProcessStartInfo
WaitForExit()
The solution is to use asynchronous reading to prevent the buffer from overflowing. Combined with the object and event processing program, the output and error data can be effectively processed within the specified timeout time. The following is an example of code:
AutoResetEvent
Through this method, you can effectively avoid dead locks, collect all outputs of standard output and standard errors, and receive notifications when data available. The printing of output and error information is added to understand the program execution results more clearly. Please make sure
<code class="language-csharp">using (Process process = new Process()) { process.StartInfo.FileName = filename; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // 进程已完成。在此处检查process.ExitCode。 Console.WriteLine("Output:\n" + output.ToString()); Console.WriteLine("\nError:\n" + error.ToString()); } else { // 超时。 Console.WriteLine("Timed out."); } } }</code>
variables have been set correctly. filename
The above is the detailed content of Why Does `ProcessStartInfo.WaitForExit()` Block, and How Can I Fix It Using Asynchronous Reads?. For more information, please follow other related articles on the PHP Chinese website!