78949

Question:
I have a MainMethod which needs to call two methods Method1 and Method2 parallel. Both of them will return list of Employee but from different database. I need to call them parallel and then combine the results of Method1 and Method2 in MainMethod and then return result to the caller of MainMethod.
I greatly appreciate if people can tell what must be signatures of methods and what code I need to write I mean async/await keywords.
Answer1:You can run them as 2 Task<T>
s. The Result property takes care of the waiting. Approximately:
// untested
Task<List<Employee>> t1 = Task.Factory.StartNew(() => Method1());
Task<List<Employee>> t2 = Task.Factory.StartNew(() => Method2());
var result = t1.Result.Concat(t2.Result);
Answer2:Using a bit more shorthand...
public static async Task<IEnumerable<Employee>> MainMethod()
{
// Await when all to get an array of result sets after all of then have finished
var results = await Task.WhenAll(
Task.Run(() => Method1()), // Note that this leaves room for parameters to Method1...
Task.Run(Method2) // While this shorthands if there are no parameters
// Any further method calls can go here as more Task.Run calls
);
// Simply select many over the result sets to get each result
return results.SelectMany(r => r);
}
for signature reference, this uses the following .NET functions:
<ul><li><a href="https://msdn.microsoft.com/en-us/library/hh194874(v=vs.110).aspx" rel="nofollow">Task.WhenAll</a></li> <li><a href="https://msdn.microsoft.com/en-us/library/hh194921(v=vs.110).aspx" rel="nofollow">Task.Run</a></li> <li><a href="https://msdn.microsoft.com/en-us/library/bb534336(v=vs.100).aspx" rel="nofollow">Enumerable.SelectMany</a> (as an extension method)</li> </ul>