Combine the result of two parallel tasks in one list

16,343

Solution 1

While many answers are close, the cleanest and most efficient option is using Task.WhenAll combined with SelectMany:

async Task<IEnumerable<Employee>> Combine()
{
    var results = await Task.WhenAll(SearchEmployeeFromDb(), GetEmployeeFromService());
    return results.SelectMany(result => result);
}

This assumes that by parallel you mean concurrently. If you wish to run these operations with multiple threads from the beginning (including the synchronous parts of the async method) you need to also use Task.Run to offload work to a ThreadPool thread:

private async Task<IEnumerable<Employee>> Combine()
{
    var results =
        await Task.WhenAll(Task.Run(() => SearchEmployeeFromDb()), Task.Run(() => GetEmployeeFromService()));
    return results.SelectMany(result => result);
}

Solution 2

You can use Task.WhenAll to create a task which will return when all supplied tasks are complete

var result = await Task.WhenAll(SearchEmployeeFromDb(),GetEmployeeFromService());
var combined = result[0].Concat(result[1]);

Solution 3

  • Start both tasks
  • Use Task.WhenAll to wait for both tasks to finish
  • Use Enumerable.Concat to combine the results


var searchEmployeesTask = SearchEmployeeFromDb();
var getEmployeesTask = GetEmployeeFromService();

await Task.WhenAll(searchEmployeesTask, getEmployeesTask);

var totalEmployees = searchEmployeesTask.Result.Concat(getEmployeesTask.Result);
Share:
16,343
nunu
Author by

nunu

Updated on June 05, 2022

Comments

  • nunu
    nunu almost 2 years

    I want to combine the result of 2 tasks in one List collection.

    Make sure that- I want to run both methods in parallel.

    Code:

    List<Employee> totalEmployees = new List<Employee>();
    

    Method1:

    public async Task<IEnumerable<Employee>> SearchEmployeeFromDb();
    

    Method2:

    public async Task<IEnumerable<Employee>> GetEmployeeFromService();
    

    Now, I want to hold the result of these two methods in totalEmployees field, also these 2 method should run asynchronously.