.NET幫助 C#並行Foreach(開發者工作方式) Curtis Chau 更新日期:6月 22, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article C# 中的 Parallel.ForEach 是什麼? Parallel.ForEach 是 C# 中的一個方法,它允許您在集合或數據源上執行並行迭代。 並行循環可以並發地執行處理,以減少整體執行時間,從而顯著提高性能。並行處理的工作原理是將工作分配到多個核心處理器中,允許任務同時運行。 這在處理相互獨立的任務時特別有用。 與依序處理每個項目的普通 foreach 循環相比,並行方法可以通過利用多個線程同時處理大量數據集以更快地完成任務。 為什麼要在 IronPDF 中使用並行處理? IronPDF is a powerful library for handling PDFs in .NET, capable of converting HTML to PDF, extracting text from PDFs, 合併或拆分文檔等。 在處理大量 PDF 任務時,使用 Parallel.ForEach 的並行處理可以顯著縮短執行時間。不論是生產數百份 PDF 還是從多個文件中提取數據,利用 IronPDF 的數據並行性確保任務更快速和高效地完成。 本指南適用於希望使用 IronPDF 和 Parallel.ForEach 優化其 PDF 處理任務的 .NET 開發人員。 建議具備 C# 的基本知識並熟悉 IronPDF 庫。 通過閱讀本指南,您將能夠實施並行處理來同時處理多個 PDF 任務,提高性能和可擴展性。 入門指南 安裝 IronPDF 要在您的項目中使用 IronPDF,需要通過 NuGet 安裝該庫。 NuGet 包安裝 要安裝 IronPDF,請按照以下步驟進行: 在 Visual Studio 中打開項目。 轉到 工具 → NuGet 套件管理器 → 為方案管理 NuGet 套件。 在 NuGet 包管理者中搜尋 IronPDF。 點擊 安裝 將 IronPDF 庫添加到您的項目中。 或者,您可以透過 NuGet 套件管理器控制台安裝它: Install-Package IronPdf 一旦安裝了 IronPDF,您就可以開始將其用於 PDF 生成功能和操作任務。 C# 中 Parallel.ForEach 的基本概念 Parallel.ForEach 是 System.Threading.Tasks 命名空間的一部分,提供了一種簡單有效的方法來同時執行迭代。 Parallel.ForEach 的語法如下: Parallel.ForEach(collection, item => { // Code to process each item }); Parallel.ForEach(collection, item => { // Code to process each item }); Parallel.ForEach(collection, Sub(item) ' Code to process each item End Sub) $vbLabelText $csharpLabel 集合中的每個項目都是並行處理的,系統決定如何在可用的線程上分配工作負載。 您還可以指定選項來控制並行度,例如使用的最大線程數。 相比之下,傳統的 foreach 循環會逐個處理每個項目,而並行循環可以同時處理多個項目,從而在處理大型集合時提高性能。 逐步實施 設置項目 首先,確保按照入門部分的說明安裝了 IronPDF。 然後,您可以開始編寫您的並行 PDF 處理邏輯。 編寫並行處理邏輯 代碼片段:使用 Parallel.ForEach 進行 HTML 到 PDF 轉換 string[] htmlFiles = { "page1.html", "page2.html", "page3.html" }; Parallel.ForEach(htmlFiles, htmlFile => { // Load the HTML content into IronPDF and convert it to PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlFile); // Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf"); }); string[] htmlFiles = { "page1.html", "page2.html", "page3.html" }; Parallel.ForEach(htmlFiles, htmlFile => { // Load the HTML content into IronPDF and convert it to PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlFile); // Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf"); }); Dim htmlFiles() As String = { "page1.html", "page2.html", "page3.html" } Parallel.ForEach(htmlFiles, Sub(htmlFile) ' Load the HTML content into IronPDF and convert it to PDF Dim renderer As New ChromePdfRenderer() Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlFile) ' Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf") End Sub) $vbLabelText $csharpLabel 此代碼演示了如何並行地將多個 HTML 頁面轉換為 PDF。 處理並行處理錯誤 在處理並行任務時,錯誤處理是至關重要的。 使用 try-catch 塊在 Parallel.ForEach 循環內管理任何異常。 代碼片段:並行 PDF 任務中的錯誤處理 Parallel.ForEach(pdfFiles, pdfFile => { try { var pdf = IronPdf.PdfDocument.FromFile(pdfFile); string text = pdf.ExtractAllText(); System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text); } catch (Exception ex) { Console.WriteLine($"Error processing {pdfFile}: {ex.Message}"); } }); Parallel.ForEach(pdfFiles, pdfFile => { try { var pdf = IronPdf.PdfDocument.FromFile(pdfFile); string text = pdf.ExtractAllText(); System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text); } catch (Exception ex) { Console.WriteLine($"Error processing {pdfFile}: {ex.Message}"); } }); Parallel.ForEach(pdfFiles, Sub(pdfFile) Try Dim pdf = IronPdf.PdfDocument.FromFile(pdfFile) Dim text As String = pdf.ExtractAllText() System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text) Catch ex As Exception Console.WriteLine($"Error processing {pdfFile}: {ex.Message}") End Try End Sub) $vbLabelText $csharpLabel 完整代碼示例的實用案例 同時從多個 PDF 中提取文本 並行處理的另一個用例是從一批 PDF 中提取文本。 在處理多個 PDF 文件時,並發地執行文本提取可以節省大量時間。以下示例演示了如何完成這一點。 示例:從多個文檔中並行提取文本 using IronPdf; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { string[] pdfFiles = { "doc1.pdf", "doc2.pdf", "doc3.pdf" }; Parallel.ForEach(pdfFiles, pdfFile => { var pdf = IronPdf.PdfDocument.FromFile(pdfFile); string text = pdf.ExtractText(); System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text); }); } } using IronPdf; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] args) { string[] pdfFiles = { "doc1.pdf", "doc2.pdf", "doc3.pdf" }; Parallel.ForEach(pdfFiles, pdfFile => { var pdf = IronPdf.PdfDocument.FromFile(pdfFile); string text = pdf.ExtractText(); System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text); }); } } Imports IronPdf Imports System.Linq Imports System.Threading.Tasks Friend Class Program Shared Sub Main(ByVal args() As String) Dim pdfFiles() As String = { "doc1.pdf", "doc2.pdf", "doc3.pdf" } Parallel.ForEach(pdfFiles, Sub(pdfFile) Dim pdf = IronPdf.PdfDocument.FromFile(pdfFile) Dim text As String = pdf.ExtractText() System.IO.File.WriteAllText($"extracted_{pdfFile}.txt", text) End Sub) End Sub End Class $vbLabelText $csharpLabel 輸出文檔 在此代碼中,每個 PDF 文件都是並行處理以提取文本,並將提取的文本保存到單獨的文本文件中。 示例:從 HTML 文件批量生成 PDF 並行處理 在這個示例中,我們將從一組 HTML 文件並行生成多個 PDF,這可能是一種典型情況,當你需要將多個動態 HTML 頁面轉換為 PDF 文檔時會出現。 代碼 using IronPdf; using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { string[] htmlFiles = { "example.html", "example_1.html", "example_2.html" }; Parallel.ForEach(htmlFiles, htmlFile => { try { // Load the HTML content into IronPDF and convert it to PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlFileAsPdf(htmlFile); // Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf"); Console.WriteLine($"PDF created for {htmlFile}"); } catch (Exception ex) { Console.WriteLine($"Error processing {htmlFile}: {ex.Message}"); } }); } } using IronPdf; using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { string[] htmlFiles = { "example.html", "example_1.html", "example_2.html" }; Parallel.ForEach(htmlFiles, htmlFile => { try { // Load the HTML content into IronPDF and convert it to PDF ChromePdfRenderer renderer = new ChromePdfRenderer(); PdfDocument pdf = renderer.RenderHtmlFileAsPdf(htmlFile); // Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf"); Console.WriteLine($"PDF created for {htmlFile}"); } catch (Exception ex) { Console.WriteLine($"Error processing {htmlFile}: {ex.Message}"); } }); } } Imports IronPdf Imports System Imports System.Threading.Tasks Friend Class Program Shared Sub Main(ByVal args() As String) Dim htmlFiles() As String = { "example.html", "example_1.html", "example_2.html" } Parallel.ForEach(htmlFiles, Sub(htmlFile) Try ' Load the HTML content into IronPDF and convert it to PDF Dim renderer As New ChromePdfRenderer() Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf(htmlFile) ' Save the generated PDF to the output folder pdf.SaveAs($"output_{htmlFile}.pdf") Console.WriteLine($"PDF created for {htmlFile}") Catch ex As Exception Console.WriteLine($"Error processing {htmlFile}: {ex.Message}") End Try End Sub) End Sub End Class $vbLabelText $csharpLabel 控制台輸出 PDF 輸出 解釋 HTML 文件:字串陣列 htmlFiles 包含您想轉換成 PDF 的多個 HTML 文件路徑。 並行處理: Parallel.ForEach(htmlFiles, htmlFile => {...}) 會對每個 HTML 文件並行處理,當處理多個文件時可以加速操作。 對於 htmlFiles 陣列中的每個文件,代碼將使用 renderer.RenderHtmlFileAsPdf(htmlFile); 將其轉換為 PDF。 保存 PDF:PDF 生成後,使用 pdf.SaveAs 方法保存,並在輸出文件名中附加原始 HTML 文件的名稱。 錯誤處理:如果發生錯誤(例如 HTML 文件不存在或轉換過程中出現問題),則會被 try-catch 塊捕捉,並且會為特定文件打印錯誤消息。 性能提示和最佳實踐 避免 IronPDF 的線程安全問題 IronPDF 在大多數操作中是線程安全的。 然而,某些操作,比如並行寫入同一文件,可能會導致問題。 務必確保每個並行任務在獨立的輸出文件或資源上執行。 優化大型數據集的並行處理 為了優化性能,考慮控制並行度。 對於大數據集來說,您可能需要限制同時線程的數量以防止系統過載。 var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }; var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 }; Dim options = New ExecutionDataflowBlockOptions With {.MaxDegreeOfParallelism = 4} $vbLabelText $csharpLabel 並行 PDF 操作中的記憶體管理 在處理大量 PDF 時,請注意記憶體使用。 請嘗試在不再需要資源時立即釋放,如 PdfDocument 對象。 使用擴展方法 擴展方法是一種特殊的靜態方法,它允許您在不修改類型源代碼的情況下為其添加新功能。 當您使用如 IronPDF 之類的庫時,如果您想添加自定義處理方法或擴展其功能,以便在並行處理場景中更便利地處理 PDF,這可能會很有用。 在並行處理中使用擴展方法的好處 通過使用擴展方法,您可以創建簡潔、可重用的代碼,簡化並行循環中的邏輯。 這種方法不僅減少了重複,而且有助於您在處理複雜的 PDF 工作流和數據並行性時保持乾淨的代碼庫。 結論 使用像 Parallel.ForEach 這樣的並行循環與 IronPDF 相結合,在處理大量 PDF 時可以實現顯著的性能提升。 不論是將 HTML 轉換為 PDF,提取文本還是操作文檔,數據並行性可以透過同時運行任務來加速執行。 並行方法確保操作可以在多個核心處理器上執行,從而縮短整體執行時間並提高批量處理任務的性能。 雖然並行處理加速了任務,但要注意線程安全和資源管理。 IronPDF 對大多數操作來說是線程安全的,但在訪問共享資源時處理潛在的衝突很重要。 考慮錯誤處理和記憶體管理以確保穩定性,特別是在應用程序擴展時。 如果您準備好深入探索 IronPDF 及其高級功能,官方文檔 提供了豐富的信息。 此外,您可以利用他們的試用許可證,允許您在正式購買前在自己的項目中測試該庫。 常見問題解答 如何在 C# 中同時將多個 HTML 文件轉換為 PDF? 您可以使用 IronPDF 和 Parallel.ForEach 方法同時將多個 HTML 文件轉換為 PDF。這種方法利用並行處理來增強效能,減少總執行時間。 在 C# 中使用 Parallel.ForEach 進行 PDF 處理有什麼好處? 使用 Parallel.ForEach 與 IronPDF 可以進行 PDF 任務的並行執行,大大提高效能,特別是在處理大量文件時。此方法利用多核來更高效地處理 HTML 到 PDF 轉換和文字擷取等任務。 如何安裝用於平行處理任務的 .NET PDF 函式庫? 要在您的 .NET 專案中安裝 IronPDF,開啟 Visual Studio,導航到工具 → NuGet 套件管理員 → 管理方案的 NuGet 套件。搜尋 IronPDF 並按安裝。或者,使用 NuGet 套件管理員控制台並輸入命令:Install-Package IronPdf。 在平行 PDF 處理中,處理錯誤的最佳做法是什麼? 在使用 IronPDF 處理平行 PDF 時,在 Parallel.ForEach 迴圈中使用 try-catch 塊來處理例外。這確保了穩健的錯誤管理,防止個別任務失敗影響整個過程。 IronPDF 能夠同時從多個 PDF 擷取文字嗎? 是的,IronPDF 可以使用 Parallel.ForEach 方法同時從多個 PDF 提取文字,實現並行處理以高效處理大型數據集。 IronPDF 是否在並行 PDF 操作中是線程安全的? IronPDF 設計為大多數操作是線程安全的。但是,重要的是要確保每個平行任務操作在不同的資源上,例如不同的文件,以避免衝突並確保數據完整性。 如何在 C# 中的平行 PDF 操作中改進記憶體管理? 為了優化記憶體管理,在使用大量 PDF 處理時,請立即釋放資源,例如 PdfDocument 物件。這有助於保持最佳記憶體使用和系統效能。 延伸方法在 C# 的平行 PDF 處理中扮演什麼角色? 延伸方法允許您在不修改其原始碼的情況下為現有型別新增功能。它們在使用 IronPDF 進行平行 PDF 處理中很有用,可創建可重用的精簡程式碼,簡化平行迴圈中的操作。 如何在 C# 中控制 PDF 任務的並行度? 在 C# 中,您可以使用 ExecutionDataflowBlockOptions 等選項來控制 PDF 任務的並行度,以限制並行線程的數量。這有助於有效管理系統資源並防止過載。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C#匿名物件(開發者如何理解其工作)C# Enumerable(它如何對開發...