Async and Await with For Loop [duplicate]

High Level – Are async/await the best choice, or should I use a different approach?

async-await is perfect for what you’re attempting to do, which is concurrently offloading multiple IO bound tasks.

What needs to be updated to allow the loop to kick off all the jobs without blocking, but not allow the function to return until all jobs are completed?

Your loop currently waits because you await each call to LoadAsync. What you want is to execute them all concurrently, than wait for all of them to finish using Task.WhenAll:

public async static Task<bool> LoadAsync(List<Schedule> scheduleList)
{
   var scheduleTaskList = scheduleList.Select(schedule => 
                          LoadAsync((int)schedule.JobId, schedule.ScheduleId)).ToList();
   await Task.WhenAll(scheduleTaskList);

   return true;
}

Leave a Comment