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);
}
List<T>is not thread-safe. Use aConcurrentBag<T>or lock around the call toAdd(which makes it pretty meaningless to use aParallel.ForEachin the first place).