Duplicate dictionary key on task list

Viewed 120

I'm trying to generate a zip file of pdfs asynchronously to speed things up as follows:

var files = new Dictionary<string, byte[]>();
var fileTasks = new List<Task<Library.Models.Helpers.File>>();

foreach (var i in groups)
{
    var task = Task.Run(async () =>
    {
        var fileName = $"{i.Key.Title.Replace('/', '-')} - Records.pdf";
        ViewBag.GroupName= i.Key.Title;
        var html = await this.RenderViewAsync("~/Views/Report/_UserRecordsReport.cshtml", i.ToList(), true);

        return await _fileUtilityService.HtmlToPDF2(html, null, fileName);
    });
    fileTasks.Add(task);
}

var completedTaskFiles = await Task.WhenAll(fileTasks);
foreach(var item in completedTaskFiles)
{
    files.Add($"{item.FileName}", item.FileResult);
}

return _fileUtilityService.GenerateZIP(files);

I'm generating all my html to pdf file tasks and waiting for them to be completed - then trying to synchronously loop through the completed tasks and add them to my dictionary for zipping but I keep getting the following error:

An item with the same key has already been added

There is no duplicate key in the list of items being added.

EDIT - so the current idea is that because its a scoped service, thats why i'm running into thread issues (attached the file utility service for information)

public class FileUtilityService : IFileUtilityService
    {
        private readonly IHttpClientFactory _clientFactory;
        public FileUtilityService(IHttpClientFactory clientFactory)
        {
        

public async Task<byte[]> HtmlToPDF(string html = null, string url = null)
        {
            try
            {
                byte[] res = null;
                if (html is null && url != null)
                {
                    var client = _clientFactory.CreateClient();
                    var requestResp = await client.GetAsync(url);
                    using var sr = new StreamReader(await requestResp.Content.ReadAsStreamAsync());
                    html = HttpUtility.HtmlDecode(await sr.ReadToEndAsync());
                }

                using(var ms = new MemoryStream())
                {
                    HtmlConverter.ConvertToPdf(html, ms);
                    res =  ms.ToArray();
                }
                return res;
                
            }catch(Exception ex)
            {
                throw ex;
            }
        }

        public async Task<Library.Models.Helpers.File> HtmlToPDF(string html = null, string url = null, string fileName = "")
        {
            return new Library.Models.Helpers.File() { FileName = fileName, FileResult = await HtmlToPDF(html, url) };
        }
0 Answers
Related