A parallel template for testing multiple subjects and possibly

I have a problem, I think it works well for concurrency, but I don’t know exactly how to express it in C #. Usually in this program I run an expensive test on several objects. I am testing to make sure β€œI can go ahead,” so I need to know if any of these tests have passed. However, if any test fails, the whole thing fails, and the whole function should be a guarantee. In pseudo code:

...
var guys = getGuysToProcess().ToList();
foreach (myGuys guy in guys) {
    if (!guy.TestForPossibleBadness())
      return false;
}

Which C # template is the best I would like to express this and test them all in parallel? If any of them fails, other tests should be discontinued, as their result does not matter.

+3
source share
3

, , , , CancelationToken, mquander.

- :

var guyTask = new List<Task<bool>>();
foreach(var guy in guys){
  guyTask.Add(Task.Factory.StartNew(()=>guy.TestForPossibleBadness());
}
var guyTaskArr = guyTask.ToArray();
var running = true;
while(true){
  var i = Task.WaitAny(guyTaskArr);
  if (!guyTaskArr[i]))
     foreach(var guy in guyTask){
         if (!guy.IsCompleted || !guy.IsFaulted){
             guy.Cancel();
         }
     }
     return false;
  }else{
     guyTask.Remove(guyTaskArr[i]);
     if (guyTask.Count == 0) return true;
     guyTaskArr = guyTask.ToArray();
  }
}

PLINQ "" IMHO

0

TPL, PLINQ:

// untested
bool ok = getGuysToProcess().AsParallel().All(g => !g.TestForPossibleBadness());

@mquan, . , ( 100%):

// untested
bool ok = ! getGuysToProcess().AsParallel().Any(g => g.TestForPossibleBadness());
+2

The PLINQ approach would be:

bool isBad = GetGuysToProcess().AsParallel().Any(g => g.TestForPossibleBadness());

Save GetGuysToProcess as a sequence, run in parallel and find the first "bad" one.

0
source

Source: https://habr.com/ru/post/1784780/


All Articles