问题
I'm trying to perform an iteration over a large set of entities to see how closely they match
i initially wrote (where MatchData is a List of structs & GenerateMatch performs an operation on two entities)
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
MatchData.Add(GenerateMatch(i, j));
Console.WriteLine("Stage :" + i + " ::: " + j);
}
}
which worked fine but was pretty slow
so i altered it to
Parallel.For(0, count, i =>
{
for (int j = i + 1; j < count; j++){
MatchData.Add(GenerateMatch(i, j));
Console.WriteLine("Stage :" + i + " ::: " + j);
}});
discounting that this will give me an enormous list, it occasionally (but not always) throws an error 'capacity was less than the current size'
being rather new to the Parallel Library i imagine that what i'm doing could be performed better (ThreadSafe?) any pointers
also as a secondary question how do I get a count on the number of i's that have been completed as i is taken out of order. Thanks
回答1:
The bug in your code is concurrent access to MatchData. Possible solution:
var matches =
from i in ParallelEnumerable.Range(0, count)
from j in ParallelEnumerable.Range(i+1, count - (i+1))
select GenerateMatch(i, j);
Just use PLINQ. You don't have to deal with synchronized collections that way.
来源:https://stackoverflow.com/questions/10651066/intermittent-capacity-was-less-than-the-current-size-error