gpt4 book ai didi

c# - 并行调用方法并组合结果

转载 作者:行者123 更新时间:2023-12-03 02:53:27 27 4
gpt4 key购买 nike

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

如果人们能够说出什么必须是方法的签名以及我需要编写什么代码(我指的是 async/await 关键字),我将非常感激。

最佳答案

使用更多的速记...

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 函数:

关于c# - 并行调用方法并组合结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30261335/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com