Penyelesaian masalah hang dengan output besar ProcessStartInfo.WaitForExit()
dalam .net, aliran output standard yang besar (mis., 7MB atau lebih) boleh menyebabkan ProcessStartInfo
hang selama -lamanya. Ini kerana saiz penampan lalai untuk output standard adalah terhad. Untuk menyelesaikannya, bacaan tak segerak diperlukan untuk mengelakkan limpahan penampan. WaitForExit()
dan StandardOutput
, menggunakan bacaan tak segerak untuk mengendalikan aliran output yang berpotensi besar dengan cekap: StandardError
<code class="language-csharp">using (Process process = new Process()) { // Process configuration... 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(); // Signal completion of output stream } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); // Signal completion of error stream } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Use a timeout to prevent indefinite waiting int timeoutMilliseconds = 10000; // Example: 10-second timeout if (process.WaitForExit(timeoutMilliseconds) && outputWaitHandle.WaitOne(timeoutMilliseconds) && errorWaitHandle.WaitOne(timeoutMilliseconds)) { // Process completed successfully within the timeout. Console.WriteLine("Output:\n" + output.ToString()); Console.WriteLine("\nError:\n" + error.ToString()); } else { // Timed out. Handle the timeout appropriately. Console.WriteLine("Process timed out."); process.Kill(); // Consider killing the process if it's unresponsive } } }</code>
untuk memberi isyarat apabila aliran output dan ralat telah dibaca sepenuhnya, menghalang benang utama daripada menyekat selama -lamanya. Penambahan waktu menyediakan satu mekanisme untuk mengendalikan situasi di mana proses itu mungkin tidak lengkap dalam jangka masa yang munasabah. Ingatlah untuk mengendalikan kes masa tamat, berpotensi membunuh proses untuk mengelakkan kebocoran sumber. AutoResetEvent
Atas ialah kandungan terperinci Kenapa `ProcessStartInfo.waitForExit ()` Hang dengan StandardOutput yang besar, dan bagaimana saya boleh memperbaikinya?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!