跳至頁尾內容
開發者更新

C#並行Foreach(開發者工作方式)

C#中的Parallel.ForEach是什麼?

Parallel.ForEach 是C#中的一個方法,它允許您在集合或資料來源上執行平行迭代。 與順序處理集合中的每個項目不同,平行迴圈可以啟用並行執行,通過減少總體執行時間顯著提高性能。平行處理通過在多個核心處理器之間分配工作來運作,允許任務同時運行。 當處理彼此獨立的任務時,這尤其有用。

與順序處理項目的普通foreach迴圈相比,平行方法可以通過平行利用多個執行緒來更快速地處理大型資料集。

為什麼要使用IronPDF進行平行處理?

IronPDF 是一個用於在.NET中處理PDF的強大程式庫,能夠將HTML轉換為PDF從PDF中提取文字合併和分割文件,等等。 在處理大量PDF任務時,使用 Parallel.ForEach 進行平行處理可以顯著減少執行時間。無論您是生成數百個PDF還是同時從多個文件提取資料,利用IronPDF的資料平行處理可確保任務完成得更快、更有效率。

本指南適用於希望使用IronPDF和Parallel.ForEach優化其PDF處理任務的.NET開發者。 建議具備C#的基本知識並熟悉IronPDF程式庫。 在本指南結束時,您將能夠實施平行處理以同時處理多個PDF任務,從而提高性能和可擴展性。

入門指南

安裝IronPDF

要在專案中使用IronPDF,您需要通過NuGet安裝該程式庫。

NuGet套件安裝

安裝IronPDF,請按照以下步驟操作:

  1. 在Visual Studio中打開您的專案。
  2. 前往 工具NuGet套件管理員為解決方案管理NuGet套件
  3. 在NuGet套件管理器中搜索IronPDF。

C# Parallel Foreach(開發人員如何工作):圖1

  1. 點擊安裝,將IronPDF程式庫新增到您的專案中。

C# Parallel Foreach(開發人員如何工作):圖2

或者,您可以通過NuGet套件管理員控制台安裝它:

Install-Package IronPdf

一旦安裝了IronPDF,您就可以開始將其用於PDF生成和操作任務。

Basic Concepts of Parallel.ForEach in C

Parallel.ForEachSystem.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。

處理平行處理錯誤

在處理平行任務時,錯誤處理至關重要。 在 Parallel.ForEach 迴圈內使用try-catch塊來管理任何異常。

程式碼片段:平行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

輸出文件

C# Parallel Foreach(開發人員如何工作):圖3

在此程式碼中,每個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

控制台輸出

C# Parallel Foreach(開發人員如何工作):圖4

PDF輸出

C# Parallel Foreach(開發人員如何工作):圖5

解釋

  1. HTML文件:陣列htmlFiles中包含多個您想要轉換為PDF的HTML文件的路徑。

  2. 平行處理:

    • Parallel.ForEach(htmlFiles, htmlFile => {...}) 平行處理每個HTML文件,這在處理多個文件時加速了操作。
    • 對於renderer.RenderHtmlFileAsPdf(htmlFile);將其轉換為PDF。
  3. 保存PDF:生成PDF後,將使用pdf.SaveAs方法保存,將輸出文件名附加為原始HTML文件的名稱。

  4. 錯誤處理:如果發生任何錯誤(例如,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# 的 PDF 處理中使用 Parallel.ForEach 有什麼好處?

與 IronPDF 配合使用 Parallel.ForEach 允許 PDF 任務的並行執行,顯著提升效能,特別是在處理大量文件時。此方法利用多個核心來更高效地處理如 HTML 至 PDF 轉換及文字提取等任務。

如何安裝用於平行處理任務的 .NET PDF 函式庫?

要為您的 .NET 專案安裝 IronPDF,打開 Visual Studio 並導航至 工具 → NuGet 套件管理員 → 管理解決方案的 NuGet 套件。搜尋 IronPDF 並點擊安裝。或者,使用 NuGet 套件管理控制台輸入命令:Install-Package IronPdf

在平行 PDF 處理中進行錯誤處理的最佳實踐是什麼?

在 IronPDF 的平行 PDF 處理中,使用 try-catch 區塊於 Parallel.ForEach 迴圈內進行錯誤處理。這確保了穩健的錯誤管理,避免個別任務失敗影響整個過程。

IronPDF 能否同時從多個 PDF 中提取文字?

可以,IronPDF 可以利用 Parallel.ForEach 方法同時從多個 PDF 中提取文字,使大資料集的處理更加高效。

IronPDF 在並行 PDF 操作中是否執行緒安全?

IronPDF 設計上大多數操作都具備執行緒安全性。然而,確保每個平行任務在不同資源上運行,例如不同的文件,以避免衝突並確保資料完整性是重要的。

如何在 C# 的平行 PDF 操作中改善記憶體管理?

為優化記憶體管理,特別是當處理大量 PDF 時,請在使用後立即釋放資源如 PdfDocument 物件。這有助於維持最佳記憶體使用和系統效能。

擴充方法在 C# 的平行 PDF 處理中扮演什麼角色?

擴充方法允許您在不修改其原始程式碼的情況下為現有型別新增功能。在 IronPDF 的平行 PDF 處理中,它們非常有用,可用於建立可重用、簡潔的程式碼,簡化平行迴圈中的操作。

如何在 C# 中控制 PDF 任務的平行度?

在 C# 中,您可以通過使用 ExecutionDataflowBlockOptions 等選項控制 PDF 任務的平行度,以限制同時執行的執行緒數目。這有助於有效管理系統資源並防止超載。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話