问题
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;
}
回答1:
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;
}
来源:https://stackoverflow.com/questions/12765329/plinq-query-need-to-know-how-many-iterations-performed