如何使用异步和多线程生成 PDF

查克尼特·宾
查克尼特·宾
2023年一月25日
更新 2024年十二月10日
分享:
This article was translated from English: Does it need improvement?
Translated
View the article in English

在批量生成或优化性能时,异步和线程在使用C#和VB.NET与IronPDF生成高性能PDF时非常有用。

开始使用IronPDF

立即在您的项目中开始使用IronPDF,并享受免费试用。

第一步:
green arrow pointer



异步示例

IronPDF 完全支持使用其异步渲染方法进行异步化,例如 RenderHtmlAsPdfAsync 方法。

:path=/static-assets/pdf/content-code-examples/how-to/async-async.cs
using IronPdf;
using System.Threading.Tasks;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

string[] htmlStrings = {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"};

// Create an array to store the tasks for rendering
var renderingTasks = new Task<PdfDocument>[htmlStrings.Length];

for (int i = 0; i < htmlStrings.Length; i++)
{
    int index = i; // Capturing the loop variable
    renderingTasks[i] = Task.Run(async () =>
    {
        // Render HTML to PDF
        return await renderer.RenderHtmlAsPdfAsync(htmlStrings[index]);
    });
}

// Wait for all rendering tasks to complete
// await Task.WhenAll(renderingTasks);

多线程示例

IronPDF 是线程安全的,并且在使用 IronPdf.ChromePdfRenderer 渲染引擎时支持多线程。

一个限制是在 macOS 机器上多线程受到限制。

我们发现Parallel.ForEach模式对于批处理PDF非常有帮助。

:path=/static-assets/pdf/content-code-examples/how-to/async-multi-thread.cs
using IronPdf;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

var queue = new List<string>() { "<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>" };

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Create a list to store the rendered PDFs
List<PdfDocument> pdfResults = new List<PdfDocument>();

Parallel.ForEach(queue, html =>
{
    // Render HTML to PDF
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

    // You may choose to save the PDF to disk here if needed
    // For this example, we'll store it in the pdfResults list
    lock (pdfResults)
    {
        pdfResults.Add(pdf);
    }
});

性能比较

让我们进行比较。 我还通过WaitFor 类用于模拟复杂 HTML 渲染,在渲染时增加了 5 秒的延迟。 以下是上述各种技术性能的比较表。

普通渲染
查克尼特·宾
软件工程师
Chaknith 负责 IronXL 和 IronBarcode 的工作。他在 C# 和 .NET 方面拥有深厚的专业知识,帮助改进软件并支持客户。他从用户互动中获得的洞察力,有助于提升产品、文档和整体体验。