-1
List<Employee> employeeList = new List<Employee>();
List<Event> eventList = new List<Event>();

//Wanted to execute each foreach call asynchronously, to improve performance
foreach (var account in accounts)
{
    var context = await GetContext(account); 
    
    //following two await is depends on above result
    var employees = await _employeeService.List(context);
    var events = await _eventService.List(context).ConfigureAwait(false);
    //Question is how to execute above two await calls parallely
    employeeList.AddRange(employees);
    eventList.AddRange(events);
}

I want to fire off two long-running tasks(employees and Events) at the same time. So maybe can we achieve parallel execution for each account above to solve this?

  • 1
    `await Task.WhenAll(accounts.Select(acc => doSomethingAsync(acc)).ToArray())` – JL0PD Jul 22 '21 at 06:13
  • 2
    https://stackoverflow.com/questions/15136542/parallel-foreach-with-asynchronous-lambda – Connell.O'Donnell Jul 22 '21 at 06:15
  • 1
    @PareshBijarane the correct term in this case is *concurrently*, not *in parallel*. You can read more about this [here](https://stackoverflow.com/questions/1050222/what-is-the-difference-between-concurrency-and-parallelism "What is the difference between concurrency and parallelism?"). – Theodor Zoulias Jul 22 '21 at 07:51

1 Answers1

5

If you want only each call inside loop to be in parallel -

List<Employee> employeeList = new List<Employee>();
List<Event> eventList = new List<Event>();
foreach (var account in accounts)
{
    var context = await GetContext(account);
    var employeesTask = _employeeService.List(context);
    var eventsTask = _eventService.List(context);
    await Task.WhenAll(employeesTask , events).ConfigureAwait(false);
    var employees = await employeesTask.ConfigureAwait(false);
    var events= await eventsTask.ConfigureAwait(false);    
    employeeList.AddRange(employees);
    eventList.AddRange(events);
}
Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20