Search code examples
c#indexoutofboundsexceptionparallel.foreach

Getting Array Index Out of bound exception while adding elements to a List in Parallel.ForEach in C#


I am trying to add elements in a List in C#. I am doing it in a Parallel.ForEach loop. I am getting Array index out of bound execption. What is the solution for this ?

var processes = new List<Process>();
Parallel.ForEach(productList, new ParallelOptions { MaxDegreeOfParallelism = 30 }, product =>
{
      // Some Logic               
      processes.Add(process);
}

Solution

  • A List<T> is not thread-safe. This means that you cannot call its Add method from more than one thread simultaneously and expect it to work.

    You should replace the list with a ConcurrentBag<T>. The other option would be to synchronize the access to the list, for example using a lock statement. But if all you do is to simply add an item to the list in your loop, it doesn't make much sense to use a Parallel.ForEach and a List<T>.