Skip to footer content

How to Generate PDFs with Async and Multithreading

In this comprehensive tutorial, we explore the process of generating PDFs asynchronously and using multi-threading in C# with the IronPDF library. To begin, ensure IronPDF is installed in your project via the NuGet package manager. Import the IronPdf namespace and set the IronPdf license key. Create an instance of the Chrome PdfRenderer class to render HTML content into PDFs. Define an array of HTML strings for conversion into PDF documents asynchronously. Initialize an array of tasks to hold the PDF rendering tasks, iterating over each HTML string. Capture the current loop variable to ensure the correct reference inside the task. Start an asynchronous task for each HTML string using Task.Run, then call the RenderHtmlAsPdfAsync method. Once the loop completes, use await Task.WhenAll method to wait for all rendering tasks to finish. For multi-threaded PDF generation, create lists for HTML strings and PDF documents. Use Parallel.ForEach to process each HTML string concurrently, rendering it as a PDF. Use a lock for thread safety while adding PDFs to the results list. Save the resulting PDF documents to disk with unique file names. The output documents are not in the same order as the HTML strings due to asynchronous execution. This tutorial provides a foundation for using IronPDF in .NET applications, encouraging exploration of its advanced features.

Further Reading: How to Generate PDFs with Async and Multithreading

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.