C#C
C#4y ago
20 replies
hellounlimited

get value from parallel for loop using Task.WhenAll

hi all, im trying to implement a parallel for loop because of some timeout issue (the normal loop will loop through large dataset and it's taking lots of time so i try to use Task.WhenAll), im trying to process all items inside this await Task.WhenAll(tasks); line but im wondering how do we get the value returned by ProcessItem method because we put them inside the WhenAll to process, can anyone help to advise? thank you so much in advance..
           IList<Note> resources = new List<Note>();
           var tasks = new List<Task>();
            foreach (var item in result)
            {
                tasks.Add(ProcessItem(item));
            }
            await Task.WhenAll(tasks); //get the value from here and initialize into the resources variable

            NoteList noteList = new NoteList ()
            {
                Resources = resources
            };
            return noteList;
            


        private async Task<IList<Note>> ProcessItem(NoteItem item)
        {
            IList<Note> resources = new List<Note>();
            var note= await getNote(item);
            Note resource = _mapper.Map<Note>(note);
            resources.Add(resource);
            return resources;
        }
Was this page helpful?