解決ProcessStartInfo.WaitForExit()阻塞問題:異步讀取方法
在某些情況下,使用ProcessStartInfo
時,程序會在WaitForExit()
處發生無限期掛起。當標準輸出緩衝區達到其限制時,就會出現此問題。重定向標準輸出和標準錯誤會加劇這個問題,從而導致死鎖。
解決方案在於使用異步讀取來防止緩衝區溢出。結合AutoResetEvent
對象和事件處理程序,可以在指定的超時時間內有效地處理輸出和錯誤數據。以下是一個代碼示例:
<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>
通過這種方法,您可以有效地避免死鎖,收集標準輸出和標準錯誤的所有輸出,並在數據可用時收到通知。 添加了輸出和錯誤信息的打印,以便更清晰地了解程序執行結果。 請確保filename
, arguments
, 和 timeout
變量已正確設置。
以上是為什麼``processstartinfo.waitforexit()`塊,如何使用異步讀取呢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!