Eric Yin
Eric Yin

Reputation: 8993

Got "Index out of bounds" Error on List.Add() in c# Parallel.ForEach

Here is the code

List<string> something = new List<string>();
Parallel.ForEach(anotherList, r =>
     {
            .. do some work
             something.Add(somedata);
      });

I get the Index out of bounds error around 1 time per hundred run. Is there anyway to prevent the conflict (I assume) caused by threading?

Upvotes: 16

Views: 7397

Answers (2)

Saeed Amiri
Saeed Amiri

Reputation: 22565

In order to prevent the issue, instead of List you may use ConcurrentQueue or similar Concurrent collections in your parallel part. Once the parallel task is done, you can put it in the List<T>.

For more information take a look at System.Collections.Concurrent namespace to find the suitable collection for your use case.

Upvotes: 23

DJ van Wyk
DJ van Wyk

Reputation: 571

I found that lock (yourObject) also negates the threading problem

Upvotes: 1

Related Questions