Parallel.Foreach maintain collection order?

Brian David Berman picture Brian David Berman · Nov 9, 2010 · Viewed 12.8k times · Source

Is there a way to guarantee order when using Parallel.ForEach()? The collection I am looping over needs to maintain it's order but I was looking for some performance improvement.

Answer

developer_ak picture developer_ak · Apr 26, 2018

In order to retain the order you must try to order the list before passing it to foreach loop since by default the Parallel.Foreach treats the list as unordered.

Example :

Parallel.ForEach(
list.AsParallel().AsOrdered(), 
(listItems) => {<operations that you need to do>});