Multithreading Support |
Most applications that create PDF documents convert for many users at once: an ASP.NET Core application handles each request on a thread of its own, and a background service often processes a queue with several workers. ExpertPdf Anywhere is built for that. Conversions running at the same time on different threads are independent of each other, and the memory and resources used by a conversion are released when it ends, so the library can run for a long time in services under a heavy load.
The rule to follow is one converter per conversion: create a new PdfConverter for each conversion and do not share an instance between threads. The same holds for a Document: documents built at the same time on different threads are safe, one document used by two threads at once is not.
The static property PdfConverterConcurrencyLevel sets how many HTML conversions run at the same time in the application. Conversions started beyond that number wait, in the order they were started, until one ends. The default value is 8; zero or a negative value removes the limit. Set it at start-up, before the first conversion.
Each conversion in flight has a Chromium browser of its own, which needs memory in proportion to the page it renders and processor time. Choose the limit from the processor cores and the memory of the server. The Chromium engine runs inside the application by default or in separate processes (see Chromium Engine); the limit applies to both.
Several threads converting at the same time, each with its own converter:
// at most 4 conversions at the same time in this application PdfConverter.PdfConverterConcurrencyLevel = 4; string[] urls = { "https://www.example.com/report1", "https://www.example.com/report2", "https://www.example.com/report3" }; System.Threading.Tasks.Parallel.For(0, urls.Length, i => { // a new converter for every conversion: converters are not shared between // threads PdfConverter pdfConverter = new PdfConverter(); pdfConverter.SavePdfFromUrlToFile(urls[i], "report" + (i + 1) + ".pdf"); });
In an application that already uses async code, such as a web application, the asynchronous methods of the converter (GetPdfBytesFromUrlAsync, SavePdfFromUrlToFileAsync and the others ending in Async) convert without keeping a thread waiting while Chromium works, and take a cancellation token:
PdfConverter pdfConverter = new PdfConverter(); byte[] pdf = await pdfConverter.GetPdfBytesFromUrlAsync( "https://www.example.com", cancellationToken);
The samples include a console application, MultithreadedPerformance, that runs many conversions on several threads and reports the throughput, to measure the converter on your own pages and server.