How to Generate PDFs with Async and Multithreading
Async and threading are crucial when generating high-performance PDFs in C# and VB.NET with IronPDF in batches or for optimized performance.
Get started with IronPDF
Start using IronPDF in your project today with a free trial.
How to Generate PDFs with Async and Multithreading
- Download IronPDF from NuGet to get started with async and multithreading PDF generation
- Prepare the HTML contents to be converted
- Use the
RenderHtmlAsPdfAsync
method to convert HTML to PDF asynchronously with IronPDF - Explore using the
Parallel.ForEach
method for multithreading in PDF processing - Review the performance comparison of different PDF generation techniques
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 to create PDF documents from HTML strings.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// Array of HTML strings to be converted into PDF documents.
string[] htmlStrings = { "<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>" };
// Create an array to store the tasks that will render the HTML strings to PDF.
var renderingTasks = new Task<PdfDocument>[htmlStrings.Length];
// Loop through each HTML string to start a new task for rendering it as a PDF.
for (int i = 0; i < htmlStrings.Length; i++)
{
int index = i; // Capture the current loop index for use within the asynchronous task.
renderingTasks[i] = Task.Run(async () =>
{
// Asynchronously render the HTML string to a PDF document.
return await renderer.RenderHtmlAsPdfAsync(htmlStrings[index]);
});
}
// Uncomment the line below to wait for all rendering tasks to complete.
// Necessary if you are calling this block within an asynchronous method.
// await Task.WhenAll(renderingTasks);
Imports IronPdf
Imports System.Threading.Tasks
' Instantiate ChromePdfRenderer to create PDF documents from HTML strings.
Private renderer As New ChromePdfRenderer()
' Array of HTML strings to be converted into PDF documents.
Private htmlStrings() As String = { "<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>" }
' Create an array to store the tasks that will render the HTML strings to PDF.
Private renderingTasks = New Task(Of PdfDocument)(htmlStrings.Length - 1){}
' Loop through each HTML string to start a new task for rendering it as a PDF.
For i As Integer = 0 To htmlStrings.Length - 1
Dim index As Integer = i ' Capture the current loop index for use within the asynchronous task.
renderingTasks(i) = Task.Run(Async Function()
' Asynchronously render the HTML string to a PDF document.
Return Await renderer.RenderHtmlAsPdfAsync(htmlStrings(index))
End Function)
Next i
' Uncomment the line below to wait for all rendering tasks to complete.
' Necessary if you are calling this block within an asynchronous method.
' await Task.WhenAll(renderingTasks);
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;
using System.Collections.Generic;
using System.Threading.Tasks;
// List of HTML strings to be converted into PDFs.
var htmlQueue = new List<string>()
{
"<h1>Html 1</h1>",
"<h1>Html 2</h1>",
"<h1>Html 3</h1>"
};
// Instantiate the ChromePdfRenderer, which is used for rendering HTML to PDF.
ChromePdfRenderer renderer = new ChromePdfRenderer();
// List for storing the rendered PDF documents.
List<PdfDocument> pdfResults = new List<PdfDocument>();
// Use Parallel.ForEach to convert each HTML string in the list to a PDF document.
Parallel.ForEach(htmlQueue, html =>
{
// Render HTML to PDF.
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
// Lock the pdfResults list when adding to make it thread-safe.
lock (pdfResults)
{
pdfResults.Add(pdf);
}
// Optionally, save the PDF document to disk.
// Uncomment the line below to save each PDF with a unique file name.
// pdf.SaveAs($"output_{Guid.NewGuid()}.pdf");
});
// Now the pdfResults list contains the PDF documents created from the HTML input.
// Optional: Perform additional operations on the pdfResults list here.
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
' List of HTML strings to be converted into PDFs.
Private htmlQueue = New List(Of String)() From {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"}
' Instantiate the ChromePdfRenderer, which is used for rendering HTML to PDF.
Private renderer As New ChromePdfRenderer()
' List for storing the rendered PDF documents.
Private pdfResults As New List(Of PdfDocument)()
' Use Parallel.ForEach to convert each HTML string in the list to a PDF document.
Parallel.ForEach(htmlQueue, Sub(html)
' Render HTML to PDF.
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
' Lock the pdfResults list when adding to make it thread-safe.
SyncLock pdfResults
pdfResults.Add(pdf)
End SyncLock
' Optionally, save the PDF document to disk.
' Uncomment the line below to save each PDF with a unique file name.
' pdf.SaveAs($"output_{Guid.NewGuid()}.pdf");
End Sub)
' Now the pdfResults list contains the PDF documents created from the HTML input.
' Optional: Perform additional operations on the pdfResults list here.
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 |
Frequently Asked Questions
What is the benefit of using async PDF generation in IronPDF?
Using async PDF generation allows the application to perform other tasks while waiting for the PDF to be generated, improving efficiency and responsiveness.
How can I start using IronPDF for async PDF generation?
You can start by downloading IronPDF from NuGet, preparing your HTML content, and using the RenderHtmlAsPdfAsync method to generate PDFs asynchronously.
Is IronPDF thread-safe for multithreading?
Yes, IronPDF is thread-safe and supports multithreading using the IronPdf.ChromePdfRenderer rendering engine, although there are limitations on macOS.
What method is used for multithreading in PDF processing with IronPDF?
The Parallel.ForEach method is used for multithreading, which is particularly useful for batch processing PDFs.
Can you provide a sample code for asynchronous PDF generation?
Yes, a sample code is provided in the guide where the RenderHtmlAsPdfAsync method is used to generate a PDF asynchronously in C#.
How does multithreaded PDF processing work in IronPDF?
Multithreaded PDF processing involves using the Parallel.ForEach loop to process each HTML string in parallel and save each resulting PDF to a file.
What is the performance comparison of different PDF generation techniques in IronPDF?
Asynchronous render took 5.59 seconds, multithreaded render took 5.68 seconds, while normal render took 15.75 seconds.
Is there a performance difference between asynchronous and multithreaded PDF generation?
Yes, there is a slight performance difference, with asynchronous render being slightly faster than multithreaded render in the provided comparison.
Why might I choose multithreading over async for PDF processing?
Multithreading is particularly useful for batch processing multiple PDFs simultaneously, leveraging multiple cores for efficiency.
What are the limitations of using IronPDF multithreading on macOS?
The guide notes there are limitations on macOS for multithreading with IronPDF, though specifics are not detailed in the excerpt provided.