Parallel loops in .NET
In this section, we will explore some examples of leveraging data parallelism in .NET projects. The parallel versions of the C# for
and foreach
loops, Parallel.For
and Parallel.ForEach
, are part of the System.Threading.Tasks.Parallel
namespace. Using these parallel loops is similar to using their standard counterparts in C#.
One key difference is that the body of the parallel loops is declared as a lambda expression. As a result, there are some changes to how you would continue or break from the parallel loops. Instead of using continue
to stop the current iteration of the loop without breaking the entire loop, you would use a return
statement. The equivalent of using break
to break out of a parallel loop is to use the Stop()
or Break()
statements.
Let’s look at an example of using a Parallel.For
loop in a .NET WinForms application.
Basic Parallel.For loops
We are going to create a new WinForms application that allows users to select a folder...