parallel foreach in csharp

To execute foreach loop in parallel, C# provides Parallel.ForEach method that can be used to process the elements in parallel. The Parallel.ForEach method essentially splits the input collection into smaller partitions and processes each partition in parallel.

Here's an example of using Parallel.ForEach method in C#:

main.cs
using System.Threading.Tasks;

// Initialize input collection
var inputCollection = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Execute foreach loop in parallel
Parallel.ForEach(inputCollection, (currentElement) =>
{
    // Do some processing on current element
    Console.WriteLine("Processing element: {0}", currentElement);
});
341 chars
12 lines

In the above example, we have initialized an input collection of integers and performed some processing on each element in parallel using Parallel.ForEach method.

Note that using parallelism in a loop can improve performance, but it also introduces additional complexity and potential issues, such as race conditions and deadlock. Therefore, it is important to carefully design and test parallel code.

gistlibby LogSnag