Getting exception when working with list and parallel loops

北慕城南 提交于 2020-12-14 06:37:13

问题


I have written a code like following below:

Parallel.ForEach(filteredList, (f) =>
{
    var conditionMatchCount = itm.AsParallel().Max(i =>
        // One point if ID matches
        ((i.ItemID == f.ItemID) ? 1 : 0) +
        // One point if ID and QuantitySold match
        ((i.ItemID == f.ItemID && i.QuantitySold == f.QuantitySold) ? 1 : 0)
    );
    // Item is missing
    if (conditionMatchCount == 0)
    {
        ListToUpdate.Add(f);
        missingList.Add(f);
    }
    // Item quantity is different
    else if (conditionMatchCount == 1)
    {
        ListToUpdate.Add(f);
    }
});

I basically have two lists:

// itm - list whos data comes from DB 
// filteredList => whos data comes from an external source

What I'm trying to achieve with the code above is to compare the two lists

and see which items from filteredList (new one) are not present in "itm" list...

If they are not present in "itm" list, they are added to

missingList.Add(f);

Also any items that have different QuantitySold property different than the one in "itm" list, I add them as well to ListToUpdate;

The error that I'm getting here is on the following line:

else if (conditionMatchCount == 1)
{
    ListToUpdate.Add(f);
}

And it says:

Destination array was not long enough. Check destIndex and length and the array's lower bounds

What am I doing wrong here?

P.S. Guys, both ListToUpdate and Missing list are plain simple lists, is that whats causing the issue here?


回答1:


Don't use List<T> with multiple threads. They aren't thread safe.

Consider using a collection from System.Collections.Concurrent.



来源:https://stackoverflow.com/questions/42007593/getting-exception-when-working-with-list-and-parallel-loops

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