5.3. Parallel Loops

One of the easiest ways to parallelize your application is by using the parallel loop construct. Two types of loops can be run in parallel:

  • Parallel.For()

  • Parallel.ForEach()

Let's take a look at these now.

5.3.1. Parallel.For()

In our example application, we will stick with the stock quote scenario described previously, create a list of stock quotes, and then iterate through them using a Parallel.For() loop construct, passing each quote into a function that will simulate a long-running process.

To see the differences between running code in serial and parallel, we will also perform this task using a standard for loop. We will use a stopwatch instance to measure the time each loop takes to complete. It is worth stressing that ...

Get Introducing .NET 4.0: with Visual Studio 2010 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.