2

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

1 Answer 1

4

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

Consider using a collection from System.Collections.Concurrent.

Sign up to request clarification or add additional context in comments.

9 Comments

For my own benefit, would using a lock be an option as well? Agree that changing the datatype is best but if this was not possible...
yea thats possible but things could suffer.
@Equalsk good point... I'd mess up the entire code if i Converted it to concurrent bag or some other ..
depending how you want to consume from it @User987, you could use a ConcurrentQueue<T> or ConcurrentStack<T>.
@User987 PLINQ only does certain things. it does not make unthread safe code thread safe.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.