Cómo generar archivos PDF con Async y Multithreading

How to Generate PDFs with Async and Multithreading

This article was translated from English: Does it need improvement?
Translated
View the article in English

Async and threading are crucial when generating high-performance PDFs in C# and VB.NET with IronPDF in batches or for optimized performance.

Quickstart: Convert HTML to PDF Asynchronously with IronPDF

Get started with asynchronous PDF generation using IronPDF in just a few lines of code.

With the RenderHtmlAsPdfAsync method, you can efficiently convert HTML content to PDF, optimizing your application's performance. This guide will show you how to leverage the power of async operations for high-performance PDF generation, perfect for batch processing and multi-threaded environments. Experience the ease and speed of IronPDF's robust capabilities.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var pdf = await IronPdf.ChromePdfRenderer.RenderHtmlAsPdfAsync("<h1>Hello World!</h1>");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Async Example

IronPDF fully supports async operation using its rendering methods such as the RenderHtmlAsPdfAsync method.

: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);
Imports IronPdf
Imports System.Threading.Tasks

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private htmlStrings() As String = {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"}

' Create an array to store the tasks for rendering
Private renderingTasks = New Task(Of PdfDocument)(htmlStrings.Length - 1){}

For i As Integer = 0 To htmlStrings.Length - 1
	Dim index As Integer = i ' Capturing the loop variable
	renderingTasks(i) = Task.Run(Async Function()
		' Render HTML to PDF
		Return Await renderer.RenderHtmlAsPdfAsync(htmlStrings(index))
	End Function)
Next i

' Wait for all rendering tasks to complete
' await Task.WhenAll(renderingTasks);
$vbLabelText   $csharpLabel

Multi-Threading Example

IronPDF is thread-safe and supports multithreading when using the IronPdf.ChromePdfRenderer rendering engine. Note that multithreading is limited on macOS machines.

The Parallel.ForEach pattern is particularly useful for batch processing PDFs.

: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);
    }
});
Imports IronPdf
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.Threading.Tasks

Private queue = New List(Of String)() From {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"}

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

' Create a list to store the rendered PDFs
Private pdfResults As New List(Of PdfDocument)()

Parallel.ForEach(queue, Sub(html)
	' Render HTML to PDF
	Dim pdf As PdfDocument = 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
	SyncLock pdfResults
		pdfResults.Add(pdf)
	End SyncLock
End Sub)
$vbLabelText   $csharpLabel

Performance Comparison

Let's perform a comparison. A 5-second delay is additionally added in rendering with the WaitFor class for simulating complex HTML rendering. Below is a comparison table of the performance using various techniques described above.

Normal Render Asynchronous Render Multithreaded Render
15.75 seconds 05.59 seconds 05.68 seconds

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF asincrónicamente en C#?

Puede convertir HTML a PDF asincrónicamente en C# usando el método RenderHtmlAsPdfAsync de IronPDF, lo que permite una generación de PDF eficiente sin bloquear el hilo principal.

¿Cuál es el beneficio de usar multithreading para el procesamiento de PDF?

El multithreading en el procesamiento de PDF con IronPDF le permite gestionar múltiples conversiones de PDF simultáneamente, lo que lo hace ideal para el procesamiento por lotes y aprovechar múltiples núcleos de CPU para un rendimiento mejorado.

¿Se puede usar IronPDF para generación de PDF tanto async como multithreaded?

Sí, IronPDF admite tanto la generación de PDF asincrónica como multithreaded. Puede usar RenderHtmlAsPdfAsync para operaciones async y Parallel.ForEach para el procesamiento multithreaded.

¿Es IronPDF seguro para hilos en la generación de PDF?

Sí, IronPDF es seguro para hilos, particularmente cuando se usa el motor de renderizado IronPdf.ChromePdfRenderer, aunque hay algunas limitaciones en macOS.

¿Cómo se compara el rendimiento de la generación de PDF async con la generación multithreaded?

En comparaciones de rendimiento, la generación de PDF asincrónica con IronPDF generalmente toma alrededor de 5,59 segundos, mientras que la generación multithreaded toma alrededor de 5,68 segundos, ambos significativamente más rápidos que la renderización normal a 15,75 segundos.

¿Cuál es un caso de uso práctico para el multithreading en el procesamiento de PDF con IronPDF?

Un caso de uso práctico para el multithreading con IronPDF es el procesamiento por lotes, donde necesita convertir un gran número de archivos HTML a PDFs simultáneamente, optimizando el uso de recursos y reduciendo el tiempo de procesamiento.

¿Hay consideraciones específicas para usar IronPDF en macOS?

Aunque IronPDF admite el multithreading, se observan limitaciones al usar esta característica en macOS. Es importante probar y verificar aplicaciones multithreaded en su entorno específico.

¿IronPDF es totalmente compatible con .NET 10?

Sí, IronPDF es compatible con .NET 10. Funciona de inmediato con proyectos .NET 10, incluidos entornos de ejecución, web, de escritorio y en contenedores, y se beneficia de las mejoras de rendimiento y lenguaje introducidas en .NET 10.
Fuentes: Página de características de IronPDF; Artículo de características de .NET 10.

Chipego
Ingeniero de Software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una Licenciatura en Ciencias en Tecnología de la Información. IronPDF e IronOCR son los dos ...
Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado