并行调用方法并组合结果

我有一个MainMethod需要调用两个方法Method1和Method2并行。 它们都将从不同的数据库返回Employee列表。 我需要将它们称为并行,然后在MainMethod中组合Method1和Method2的结果,然后将结果返回给MainMethod的调用者。

我非常感谢人们能说出必须签名的方法和我需要编写的代码是什么意思是async / await关键字。

您可以将它们作为2 Task运行。 Result属性负责等待。 大约:

 // untested Task> t1 = Task.Factory.StartNew(() => Method1()); Task> t2 = Task.Factory.StartNew(() => Method2()); var result = t1.Result.Concat(t2.Result); 

用一点简写……

 public static async Task> 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); } 

对于签名引用,它使用以下.NET函数:

  • Task.WhenAll
  • Task.Run
  • Enumerable.SelectMany (作为扩展方法)