如何将Task.WhenAll()实现转换为Parallel.ForEach()?

时间:2018-07-03 19:40:08

标签: c# .net parallel-processing parallel.foreach

我下面有代码检查跨域的用户组授权。该代码使用多种域组合来检查授权:

//build domain combos for lookup
var domainCombos = new List<Tuple<string, string>>();
domainCombos.Add(new Tuple<string, string>("corp-domain-1", "corp-domain-1"));
domainCombos.Add(new Tuple<string, string>("corp-domain-1", "corp-domain-2"));
domainCombos.Add(new Tuple<string, string>("corp-domain-2", "corp-domain-2"));
domainCombos.Add(new Tuple<string, string>("corp-domain-2", "corp-domain-1"));

var results = await Task.WhenAll(domainCombos.Select(domainCombo =>
{
    request.GroupDomainName = domainCombo.Item1;
    request.UserDomainName = domainCombo.Item2;
    return GetSingleAuthorizedGroupInfo(request);
}));
var aggregateResults = results.Where(x => x != null).SelectMany(result => result).ToList();
return aggregateResults;

我认为该例程似乎是Parallel.ForEach b / c的不错选择,对GetSingleAuthorizedGroupInfo()的调用之间没有相互依赖关系。

此外,当我使用1 domainCombo执行时,响应将在800ms内返回,而当我使用4 domainCombos执行时,响应将在1800ms内返回。我将如何转换上面的代码以利用Parallel.ForEach?

0 个答案:

没有答案