2

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);
}
3
  • 5
    A List<T> is not thread-safe. Use a ConcurrentBag<T> or lock around the call to Add (which makes it pretty meaningless to use a Parallel.ForEach in the first place). Commented Aug 29, 2019 at 11:23
  • 1
    Actually, introducing a lock shouldn't be that big of a problem. Sure, it'll make adding items to the list be a sequential operation, but I'm assuming the cost of doing that isn't the biggest thing you have in the parallel code, so most of it will still run in parallel. Commented Aug 29, 2019 at 11:33
  • True. its not the biggest thing i am doing in the loop. lock solution is also fine but i think delegating synchronization work to the framework itself is a better approach then adding lock explicitly in code :) Commented Aug 29, 2019 at 11:41

1 Answer 1

3

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>.

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

Comments

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.