Call methods in parallel and combine the results

I have MainMethod that needs to call two methods Method1 and Method2 parallel. Both of them will return the Employee list, but from a different database. I need to call them in parallel and then combine the results of Method1 and Method2 in MainMethod and then return the result to the calling MainMethod device.

I really appreciate it if people can tell me what method signatures should be and what code I need to write. I mean the async / await keywords.

+1
c # parallel-processing
May 15 '15 at
source share
2 answers

You can run them as 2 Task<T> s. The Result property takes care of the wait. About:

 // untested Task<List<Employee>> t1 = Task.Factory.StartNew(() => Method1()); Task<List<Employee>> t2 = Task.Factory.StartNew(() => Method2()); var result = t1.Result.Concat(t2.Result); 
+1
May 15 '15 at 14:04
source share

Using a little shorter ...

 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); } 

to reference the signature, it uses the following .NET features:

+1
May 15 '15 at 15:49
source share



All Articles