private static async Task PdfBuilderProc() { using var scope = serviceProvider.CreateScope(); var imageRepository = scope.ServiceProvider.GetRequiredService <IImageRepositoryService>(); var pdfBuilder = scope.ServiceProvider.GetRequiredService <IPdfBuilderService>(); var nextDocument = nextDocumentService.GetNextDocument(); int take = conveyorOptions.AmountImagesInPdf; do { using var imagesCollection = await imageRepository.GetImages(skip : nextDocument.skip, take : take); if (imagesCollection.Images.Count == 0) { break; } try { var pdfDocument = new PdfDocument($"{conveyorOptions.BasePdfDocumentName}_{nextDocument.documentNumber}", DocumentPageSize.A4); pdfDocument.AddPages(imagesCollection.Images .Select(image => { return(new PdfPage { DataStream = image.DataStream, }); }) .ToArray()); pdfBuilder.BuildDocument(conveyorOptions.OutputDirectory, pdfDocument); } catch (Exception e) { logger.Error(e, "Can not create pdf document"); } lock (lockObject) { amountProcessedImages += imagesCollection.Images.Count; } nextDocument = nextDocumentService.GetNextDocument(); }while (true); }