Cómo generar PDFs con Async y Multithreading

Chipego
Chipego Kalinda
25 de enero, 2023
Actualizado 10 de diciembre, 2024
Compartir:
This article was translated from English: Does it need improvement?
Translated
View the article in English

Async y threading son útiles al generar PDFs de alto rendimiento en C# y VB.NET con IronPDF en lotes o para un rendimiento optimizado.

Comience con IronPDF

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer



Ejemplo asíncrono

IronPDF admite completamente Async usando sus métodos de Renderización Asíncrona, como el método 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);
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

Ejemplo de multihilo

IronPDF es thread-safe y soporta multithreading cuando se utiliza el motor de renderizado IronPdf.ChromePdfRenderer.

Una limitación es que el multithreading está limitado en máquinas macOS.

Hemos encontrado el patrón Parallel.ForEach muy útil para el procesamiento por lotes de 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

Comparación de resultados

Hagamos una comparación. Además, he añadido un retraso de 5 segundos en la renderización con la clase WaitFor para simular la renderización de HTML complejo. A continuación se muestra una tabla comparativa de los resultados obtenidos con las distintas técnicas descritas.

Renderizado Normal
Chipego
Ingeniero de software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y a ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una licenciatura en Tecnología de la Información. IronPDF e IronOCR son los dos productos en los que Chipego se ha centrado, pero su conocimiento de todos los productos crece día a día, a medida que encuentra nuevas formas de ayudar a los clientes. Disfruta de lo colaborativa que es la vida en Iron Software, con miembros del equipo de toda la empresa que aportan su variada experiencia para contribuir a soluciones eficaces e innovadoras. Cuando Chipego está lejos de su escritorio, a menudo se le puede encontrar disfrutando de un buen libro o jugando al fútbol.