PLINQ query, need to know how many iterations performed
Asked Answered
W

1

0

what I'm basically doing is iterating in parallel over a sequence of letter combinations, when I get the combo I want it's considered a win. I want to get all the wins from this query (which it's doing correctly), but the trick has been how to keep track of the number of times the test for a win was executed (basically the method that returns true/false that it won).

I'm creating an instance variable in the class that increments each time the test on the combo is performed, but each time I run the process I get a different number for this instance variable. I realize it's a threading issue, but I'm not sure how to resolve it.

There's a max limit for the number of wins that when this is hit the query needs to stop. If I didn't have that constraint I wouldn't need to know the number of times a combo is run obviously, as it would run all the combos, but as you see I need to break out of the query when I hit the max limit.

public Results GetWinResults()
{
         ParallelQuery<string> winningCombos = from n in _nextCombination.GetNextCombo().AsParallel()                                          
                       where processNextCombo(n) // where there was a win
                       select n;

         List<string> wins = new List<string>();

         foreach (var winningCombo in winningCombos)
         {
               wins.Add(winningCombo);
               if (wins.Count == winsMaxLimit)
                  break;
         }

         return new Results { Wins = wins, CombosTried = totalCombosRun };
 }


 private bool processNextCombo(string combo)
 {
     totalCombosRun++;
     // do tests to see if combo was a winner
     if (didWin)
        return true;
     return false;
 }
Welldone answered 7/10, 2012 at 1:18 Comment(0)
A
2

You can use the Interlocked class to increment an int in a threadsafe fashion:

 int totalCombosRun=0;

 private bool processNextCombo(string combo)
 {
     Interlocked.Increment(ref totalCombosRun);
     // do tests to see if combo was a winner
     if (didWin)
        return true;
     return false;
 }
Acidophil answered 7/10, 2012 at 1:23 Comment(1)
thanks. Wasn't sure if there was something you can do in the LINQ statement to aggregate the number of times, but I guess this will work.Welldone

© 2022 - 2024 — McMap. All rights reserved.