I dont have much experiance with async methods and I am not sure if I am using parallel for each correctly. In some cases I am getting Index out of range exception on the line with: "listPages.Add"
private static int SetPages(FileDocument document, List<PageDTO> pages, string tableName, Entities entity, int accessID)
{
   List<Page> listPages = new List<Page>();
            
    Parallel.ForEach(pages, new ParallelOptions { MaxDegreeOfParallelism = 8 }, page =>
    {
        string docPath = GetPathString(page.PageID);
        if (File.Exists(docPath))
        {
            byte [] docBytes = ConvertToWebP(docPath);
            if(docBytes.Length > 0)
            {
                var fileStreamID = InsertInDatabase(docBytes, page.PageID, tableName);
                listPages.Add(SetPage(document, page.PageNumber, fileStreamID, tableName, accessID));
            }
        }
    });
            
    entity.FilePages.AddRange(listPages);
    return listPages.Count();
}