0

I have the code below which checks for user group authorization across domains. The code checks for authorization using a various combination of domains:

//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;

I think that this routine appears to be a good candidate for Parallel.ForEach b/c there are no interdependencies between calls to GetSingleAuthorizedGroupInfo().

Also, when I execute with 1 domainCombo, the response returns in 800ms, whereas when I execute with 4 domainCombos the response returns in about 1800ms. How would I go about converting the code above to leverage Parallel.ForEach?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
user9393635
  • 1,369
  • 4
  • 13
  • 32
  • 1
    this code already runs parallel, what advantage do you expect to gain from using Parallel.ForEach ? – Vladi Pavelka Jul 03 '18 at 19:45
  • Why can't you just use a loop (for or foreach) do instantiate all the tasks and put them into a task array and then use `Task.WaitAll(taskArr);` ? This will fire `n` threads and your function will return once all tasks are done, but they will be running in parallel. – bmvr Jul 03 '18 at 19:45
  • @bmvr are there any advantages to Task.WaitAll() over Task.WhenAll()? – user9393635 Jul 03 '18 at 19:55
  • 1
    @user9393635 no, but there is a disadvantage of synchronously blocking on async code – Vladi Pavelka Jul 03 '18 at 19:58
  • Does your code execute `async` operations? Or is `GetSingleAuthorizedGroupInfo` purely CPU bound? This is the first question you should ask yourself. CPU bound operations are good candidates for parallel work, `async` operations (HTTP requests and IO operations in general), instead, are not, and should be awaited (like you already do). – Federico Dipuma Jul 03 '18 at 21:29
  • @bmvr `Task.WaitAll()` is a synchronization method while `Task.WhenAll()` is an asynchronous method. They are basically the same but you should notice that when you use synchronization waiting for asynchronous methods, you might got dead-block. – walterlv Jul 04 '18 at 00:03
  • Related: [ForEachAsync with Result](https://stackoverflow.com/questions/30907650/foreachasync-with-result). – Theodor Zoulias Feb 07 '23 at 05:23

0 Answers0