首頁 > 後端開發 > C++ > 為什麼``processstartinfo.waitforexit()`塊,如何使用異步讀取呢?

為什麼``processstartinfo.waitforexit()`塊,如何使用異步讀取呢?

Barbara Streisand
發布: 2025-01-29 20:26:11
原創
236 人瀏覽過

Why Does `ProcessStartInfo.WaitForExit()` Block, and How Can I Fix It Using Asynchronous Reads?

解決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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板