
C# 并行 Foreach(开发者用法)
什么是C#中的Parallel.ForEach?
Parallel.ForEach 是 C# 中的一个方法,允许您对集合或数据源进行并行迭代。 通过并行循环替代对集合中每个项目的顺序处理,可以显著提高性能,缩短整体执行时间。并行处理通过将工作分配到多个核心处理器来实现,使任务能够同时运行。 这对于处理相互独立的任务特别有用。
与顺序处理项目的常见 foreach 循环相比,并行方法可以通过利用多个线程并行处理大型数据集,从而更快地处理。
为什么要在 IronPDF 中使用并行处理?
IronPDF 是用于在 .NET 中处理 PDF 的强大库,可以 将 HTML 转换为 PDF,从 PDF 中提取文本,合并和拆分文档,等等。 当处理大量 PDF 任务时,使用 Parallel.ForEach 并行处理可以显著缩短执行时间。无论是生成数百个 PDF 还是同时从多个文件中提取数据,利用 IronPDF 的数据并行性可以确保任务更快更有效地完成。
本指南旨在帮助 .NET 开发人员优化其使用 IronPDF 和 Parallel.ForEach 进行 PDF 处理的任务。 推荐具备 C# 的基础知识和对 IronPDF 库的熟悉。 在本指南结束时,您将能够实现并行处理以同时处理多个 PDF 任务,提高性能和可伸缩性。
开始
安装 IronPDF
要在项目中使用 IronPDF,您需要通过 NuGet 安装该库。
NuGet软件包安装
安装 IronPDF 的步骤如下:
1.在 Visual Studio 中打开您的项目。 2. 转到 工具 → NuGet 包管理器 → 为解决方案管理 NuGet 包。 3. 在NuGet包管理器中搜索IronPDF。

- 点击 安装 将 IronPDF 库添加到您的项目中。

或者,您可以通过 NuGet 包管理器控制台安装它:
PM > Install-Package IronPdf
一旦安装了 IronPDF,您就可以开始使用它来进行 PDF 生成和操作任务。
Basic Concepts of Parallel.ForEach in C#
System.Threading.Tasks命名空间的一部分,并提供了一种简单有效的方法来同时执行迭代。 Parallel.ForEach的语法如下:
Parallel.ForEach(collection, item =>
{
// Code to process each item
});Parallel.ForEach(collection, Sub(item)
' Code to process each item
End Sub)集合中的每个项目都是并行处理的,系统决定如何在可用的线程间分配工作负载。 您也可以指定选项来控制并行的程度,例如使用的最大线程数。
相比之下,传统的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");
});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, 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);
});
}
}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}");
}
});
}
}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文件的路径。 -
并行处理:
Parallel.ForEach(htmlFiles, htmlFile => {...})并行处理每个HTML文件,在处理多个文件时加快了操作速度。- 对
renderer.RenderHtmlFileAsPdf(htmlFile);将其转换为PDF。
-
**保存PDF:**生成PDF后,使用
pdf.SaveAs方法保存,并将输出文件名附加上原HTML文件的名称。 -
**错误处理:**如果出现任何错误(例如 HTML 文件不存在或转换过程中出现问题),try-catch 块捕获它,并为特定文件打印错误信息。
性能提示和最佳实践
避免 IronPDF 的线程安全问题
IronPDF 对大多数操作都是线程安全的。 然而,一些操作,例如并行写入同一文件,可能会引发问题。 始终确保每个并行任务操作一个单独的输出文件或资源。
优化大数据集的并行处理
要优化性能,请考虑控制并行性程度。 对于大型数据集,您可能希望限制并发线程的数量,以防止系统过载。
var options = new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4
};Dim options = New ExecutionDataflowBlockOptions With {.MaxDegreeOfParallelism = 4}并行 PDF 操作中的内存管理
在处理大量 PDF 时,请注意内存使用。 尝试尽快释放像PdfDocument对象这样不再需要的资源。
使用扩展方法
扩展方法是一种特别的静态方法,允许您向现有类型添加新功能,而无需修改其源代码。 这在使用像 IronPDF 这样的库时很有用,您可能想要添加自定义处理方法或扩展其功能,以便在并行处理场景下更便捷地处理 PDF。
在并行处理中使用扩展方法的好处
通过使用扩展方法,您可以创建简洁可重用的代码,简化并行循环中的逻辑。 这种方法不仅减少了重复,还能在处理复杂的 PDF 工作流程和数据并行时,帮助您维护一个干净的代码库。
结论
使用类似Parallel.ForEach的并行循环与IronPDF一起处理大量PDF时,提供了显著的性能提升。 无论是将 HTML 转换为 PDF、提取文本还是操作文档,数据并行性通过同时运行任务实现更快的执行。 并行方法通过跨多个核心处理器执行操作,减少整体执行时间,并提高批处理任务的性能。
虽然并行处理加快了任务执行速度,但要注意线程安全和资源管理。 IronPDF 对大多数操作是线程安全的,但在访问共享资源时必须留意潜在冲突。 考虑错误处理和内存管理以确保稳定性,尤其是在应用程序扩展时。
如果您准备深入研究 IronPDF 并探索高级特性,官方文档提供了广泛的信息。 此外,您可以利用他们的试用许可证,允许您在自己的项目中测试该库,然后再决定购买。

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.
Related Articles


