并行调用方法并合并结果

Call methods parallel and combine results

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

如果有人能告诉我什么必须是方法的签名以及我需要编写什么代码,我将不胜感激。我的意思是 async/await 个关键字。

您可以 运行 它们作为 2 Task<T> 秒。结果 属性 负责等待。大约:

// untested 
Task<List<Employee>> t1 = Task.Factory.StartNew(() => Method1());
Task<List<Employee>> t2 = Task.Factory.StartNew(() => Method2());

var result = t1.Result.Concat(t2.Result);

多用一点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);
}

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