Can we add new elements to a list using Parallel.ForEach()?

clewaks picture clewaks · Apr 14, 2012 · Viewed 12.8k times · Source

My code does very simple stuff

list already has elements. I have approximately 25000 elements (and I'm expecting to have more) in the list and each element is small (DateTime).

List<DateTime> newList = new List<DateTime>();
Parallel.ForEach(list, l => newlist.Add(new DateTime(l.Ticks + 5000)));

i.e, based on each element, I'm creating new elements and adding them to a different list. But, this doesn't seem to be a good programming approach. I hit this exceptions some times, but not everytime.

IndexOutOfRangeException : {"Index was outside the bounds of the array."}

Can we add elements to a list using Parallel.ForEach()? If yes, why do I hit the error? If no, why?

Answer

Gabe picture Gabe · Apr 14, 2012

What you would really want in this situation is more like this:

newlist = list.AsParallel().Select(l => new DateTime(l.Ticks + 5000)).ToList();

Although you should measure the performance to see if this situation even benefits from parallelization.