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 中打开您的项目。
- 转到 工具 → NuGet 包管理器 → 为解决方案管理 NuGet 包。
- 在NuGet包管理器中搜索IronPDF。

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

或者,您可以通过 NuGet 包管理器控制台安装它:
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, 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");
});
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文件的路径。 - 并行处理:
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
};
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 并探索高级特性,官方文档提供了广泛的信息。 此外,您可以利用他们的试用许可证,允许您在自己的项目中测试该库,然后再决定购买。
常见问题解答
如何在 C# 中同时将多个 HTML 文件转换为 PDF?
您可以使用 IronPDF 和 Parallel.ForEach 方法同时将多个 HTML 文件转换为 PDF。此方法利用并发处理来减少总执行时间,从而提高性能。
在 C# 中使用 Parallel.ForEach 进行 PDF 处理的好处是什么?
using IronPDF 的 Parallel.ForEach 允许 PDF 任务的并发执行,显著提高性能,特别是在处理大量文件时。此方法利用多核来更高效地处理 HTML 到 PDF 转换和文本提取等任务。
如何安装用于并行处理任务的 .NET PDF 库?
要为您的 .NET 项目安装 IronPDF,请打开 Visual Studio,然后导航到 Tools → NuGet Package Manager → Manage NuGet Packages for Solution。搜索 IronPDF 并点击 Install。或者,使用 NuGet Package Manager Console 并运行命令:Install-Package IronPDF。
并行 PDF 处理中的错误处理最佳实践是什么?
在使用 IronPDF 进行并行 PDF 处理时,在 Parallel.ForEach 循环中使用 try-catch 块来处理异常。这确保了可靠的错误管理,并防止单个任务失败影响整体过程。
IronPDF 可以同时处理多个 PDF 的文本提取吗?
是的,IronPDF 可以通过使用 Parallel.ForEach 方法同时从多个 PDF 中提取文本,实现高效处理大数据集的并发处理。
IronPDF 是否支持线程安全的并发 PDF 操作?
IronPDF 设计为大多数操作是线程安全的。然而,需要确保每个并行任务在单独的资源上运行,例如不同的文件,以避免冲突并确保数据完整性。
如何在 C# 中提高并行 PDF 操作的内存管理?
为优化内存管理,使用后及时释放诸如 PdfDocument 对象等资源,尤其是在处理大量 PDF 时。这有助于保持最佳的内存使用和系统性能。
扩展方法在 C# 中的并行 PDF 处理中起什么作用?
扩展方法允许在不修改源代码的情况下为现有类型添加功能。它们在使用 IronPDF 进行并行 PDF 处理时非常有用,旨在创建可重用的、简洁的代码,简化并行循环中的操作。
如何控制 C# 中 PDF 任务的并行度?
在 C# 中可以通过使用诸如 ExecutionDataflowBlockOptions 之类的选项来限制并发线程的数量,以控制 PDF 任务的并行度。这有助于有效管理系统资源并防止过载。




