非同期およびマルチスレッドを使用してPDFを生成する方法

チャクニット・ビン
チャクニット・ビン
2023年1月25日
更新済み 2024年12月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メソッドなどのAsync Renderingメソッドを使用してAsyncを完全にサポートしています。

: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マシンではマルチスレッドが制限されています。

私たちは、PDFのバッチ処理においてParallel.ForEachパターンが非常に役立つことを発見しました。

: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);
    }
});

パフォーマンス比較

比較を行いましょう。 さらに、複雑なHTMLレンダリングをシミュレートするために、WaitForクラスを使用して5秒の遅延を追加しました。 以下は、上記で説明したさまざまな技術を使用したパフォーマンスの比較表です。

Normal Render Asynchronous Render Multithreaded Render
15.75 seconds 05.59 seconds 05.68 seconds
チャクニット・ビン
ソフトウェアエンジニア
ChaknithはIronXLとIronBarcodeで作業しています。彼はC#と.NETに深い専門知識を持ち、ソフトウェアの改善と顧客サポートを支援しています。ユーザーとの対話から得た彼の洞察は、より良い製品、文書、および全体的な体験に貢献しています。