I understand that when using TPL Parallel.ForEach, we do not need to explicitly write code to "wait" for the tasks inside it to complete. However, I am doing a simple transfer of 1000 elements from a source list into a destination list. On setting a breakpoint OUTSIDE and AFTER the Parallel.ForEach loop, I see an invalid/incomplete count of the items in the destination list... Why?
List<int> myList = new List<int> { };
for (int i = 0; i < 1000; i++) {
myList.Add(i);
}
List<int> newList = new List<int>();
Parallel.ForEach(myList, x => {
newList.Add(x);
});
Thread.Sleep(5000);
var test = newList.Count;
List
isn't thread-safe so you can't use that in parallel code. You should use ConcurrentBag
(or any other thread-safe collection) instead:
var bag = new ConcurrentBag<int>();
Parallel.ForEach(myList, x =>
{
bag.Add(x);
});
You could also use a lock
around the newList
but that would make the parallelization useless.