Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine the result of two parallel tasks in one list

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.

like image 460
nunu Avatar asked Dec 01 '14 12:12

nunu


2 Answers

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);
}
like image 103
i3arnon Avatar answered Sep 20 '22 15:09

i3arnon


  • 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);
like image 30
dcastro Avatar answered Sep 16 '22 15:09

dcastro