Async and Await with For Loop
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;
}
For fan-out parallel async calls, you want to fire off the Task's to start them running, but then handle them as async future or promise values. You can just synchronize / await them at the end when all are finished.
Simplest way to do this is to turn your for-loop into something like this:
List<Task<bool>> jobs = new List<Task<bool>>();
foreach (var schedule in scheduleList)
{
Task<bool> job = LoadAsync((int) schedule.JobId, schedule.ScheduleId); // Start each job
jobs.Add(job);
}
bool[] finishedJobStatuses = await Task.WhenAll(jobs); // Wait for all jobs to finish running
bool allOk = Array.TrueForAll(finishedJobStatuses, p => p);