并行调用方法并合并结果 [英] Call methods parallel and combine results
问题描述
我有一个MainMethod,它需要并行调用两个方法Method1和Method2.他们两个都将从不同的数据库返回Employee列表.我需要并行调用它们,然后在MainMethod中合并Method1和Method2的结果,然后将结果返回给MainMethod的调用者.
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.
推荐答案
您可以将它们作为2个Task<T>
运行. Result属性负责等待.大约:
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);
这篇关于并行调用方法并合并结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!