intermittent capacity was less than the current size Error

喜夏-厌秋 提交于 2020-01-30 09:12:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!