First, we will write an example using the standard sequential Foreach loop and will see how much time it will take to complete the execution. Let us understand Parallel Foreach with an example. The delegate’s parameter contains the item from the collection that is to be processed during the iteration. The second parameter accepts an Action delegate, usually expressed as a lambda expression that determines the action to take for each item in the collection. This can be any collection that implements IEnumerable. The first one is the collection of objects that will be enumerated. This is the simplest overloaded version that accepts two arguments. There are many overloaded versions available for this method. The parallel version of the loop uses the static ForEach method of the Parallel class. Note: We need to use parallel loops such as Parallel.For and Parallel.ForEach method to speed up operations where an expensive, independent operation needs to be performed for each input of a sequence. So, the loop is ideally suited to processes where each iteration is independent of the others. This may open the possibility of synchronization problems. However, the Parallel Foreach method executes multiple iterations at the same time on different processors or processor cores. In a standard Foreach loop, each iteration processes a single item from the collection and will process all the items one by one only. The Parallel ForEach in C# provides a parallel version of the standard, sequential Foreach loop. Here, in this article, I am going to keep the focus on the Parallel Foreach method in C#.
In our previous article, we already discussed the Parallel for Method in C#with examples. Parallel.For and Parallel.Foreach) which are conceptually the “for” and “for each” loops, except that, they use multiple threads to execute multiple iterations at the same time on a machine with multiple cores. As we already discussed in our previous article that the Task Parallel Library (TPL) provides two methods (i.e. In this article, I am going to discuss the Parallel Foreach in C# with examples.