C#並行Foreach(開發者工作方式)
什麼是 C# 中的 Parallel.ForEach?
Parallel.ForEach 是 C# 中的一種方法,可讓您在集合或資料來源上執行平行迭代。 並行迴圈並不是依序處理集合中的每個項目,而是實現並發執行,這可以減少整體執行時間,從而顯著提高性能。平行處理的工作方式是將工作分派給多個核心處理器,讓任務可以同時執行。 這在處理彼此獨立的任務時尤其有用。
一般的 foreach 循環會依序處理項目,相較之下,並行方式則可利用多個線程並行處理大型資料集,速度更快。
為何使用 IronPDF 進行平行處理?
IronPDF 是一個功能強大的函式庫,用於在 .NET 中處理 PDF,能夠 將 HTML 轉換為 PDF、從 PDF 中萃取文字、merging and splitting documents 等。 在處理大量 PDF 任務時,使用 Parallel.ForEach 進行平行處理可大幅縮短執行時間。無論您是要一次產生數百個 PDF,或是從多個檔案中抽取資料,利用 IronPDF 的資料並行性都能確保任務更快速、更有效率地完成。
本指南面向希望使用 IronPDF for .NET 和 Parallel.ForEach 優化 PDF 處理任務的 .NET 開發人員。 建議具備 C# 的基本知識,並熟悉 IronPDF 函式庫。 在本指南結束時,您將能夠實現並行處理,以同時處理多個 PDF 任務,從而提高性能和可擴展性。
開始
安裝 IronPDF。
若要在專案中使用 IronPDF,您需要透過 NuGet 安裝函式庫。
NuGet 套件安裝
要安裝 IronPDF,請遵循以下步驟:
1.在 Visual Studio 中開啟您的專案。 2.前往 工具 → NuGet套件管理員 → 管理解決方案的NuGet套件。 3.在 NuGet 套件管理器中搜尋 IronPDF。

4.按一下 安裝,將 IronPDF 函式庫新增至您的專案。

另外,您也可以透過 NuGet 套件管理員控制台進行安裝:
Install-Package IronPdf
安裝 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)
集合中的每個項目都會進行平行處理,系統會決定如何在可用的線程間分配工作量。 您也可以指定選項來控制平行程度,例如使用的最大線程數。
相較之下,傳統的循環逐一處理每個項目,而平行循環可以同時處理多個項目,從而在處理大型集合時提高效能。
逐步實施
設定專案
首先,確保 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)
此程式碼示範如何平行地將多個 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)
包含完整程式碼範例的實用案例
同時從多個 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
輸出文件

在此程式碼中,每個 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
控制台輸出

PDF輸出

說明
- HTML 檔案:陣列
htmlFiles包含多個要轉換為 PDF 的 HTML 檔案的路徑。
2.平行處理:
Parallel.ForEach(htmlFiles, htmlFile => {...})並發處理每個 HTML 文件,從而加快處理多個文件時的操作速度。- 對於
htmlFiles陣列中的每個文件,程式碼使用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}
並行 PDF 作業中的記憶體管理
在處理大量 PDF 時,請注意記憶體的使用。 一旦不再需要 PdfDocument 物件之類的資源,就應盡快釋放它們。
使用擴充方法
擴充方法是一種特殊的靜態方法,可讓您在不修改現有類型的原始碼的情況下,為該類型新增新功能。 這在使用 IronPDF 之類的函式庫時非常有用,您可能想要新增自訂處理方法或擴充其功能,讓處理 PDF 更為方便,尤其是在平行處理的情況下。
在平行處理中使用擴充方法的好處
透過使用擴充方法,您可以建立簡潔、可重複使用的程式碼,簡化平行迴圈中的邏輯。 這種方法不僅能減少重複,還能幫助您維護乾淨的程式碼庫,尤其是在處理複雜的 PDF 工作流程和資料平行性時。
結論
在IronPDF中使用類似 Parallel.ForEach 的平行循環,在處理大量 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 任務的並行度,以限制並行線程的數量。這有助於有效管理系統資源並防止過載。



