The Parallel class
The Parallel class is optimized for iterations and its behavior is even better—in loops—than PLINQ, although the difference is not meaningful. However, there are situations in which a fine-tuning of loops can noticeably increase the user experience.
The class has variants of the for
and foreach
methods (also invoke
, but it is rare to see this in practice), which can be used in loops when we think the performance can be clearly slowed down using the nonparallel versions.
If we take a look at the definition of the Parallel.For
version, we'll see that it receives a couple of numbers (int
or long
) to define the scope of the loop and an Action
, which relates to the functionality to be executed.
Let's test this with a example that is similar, but not exact, to the previous one. We'll use the same IsPrime
algorithm, but this time, we'll write the results checking one by one inside a for
loop. So, we start with a simple loop that checks the first 1000 numbers and loads the result...