O'Reilly logo

Professional Visual Basic 2012 and .NET 4.5 Programming by Todd Herman, Gastón Hillar, David McCarter, Rob Windsor, Billy Hollis, Bill Sheldon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Parallelizing Loops

Both GenerateAESKeys and GenerateMD5Hashes represent an opportunity to run iterations in parallel. They generate the input data to simplify the example and perform the same operation for each piece. Thus, it represents a data parallelism scenario. It is possible to refactor the loops to run the operations in parallel. This way, instead of running both subroutines in parallel, each one can take full advantage of parallelism and automatically scale according to the number of existing logical cores.

Parallel.For

You can think of refactoring an existing For loop to take advantage of parallelism as a simple replacement of For with Parallel.For. Unfortunately, it isn't as simple as that.

The following code snippets refactor the subroutines shown in the preceding section, showing the code for both the original loops and the new code with the refactored loops using the imperative syntax to implement the data parallelism offered by Parallel.For. The new methods, ParallelGenerateAESKeys and ParallelGenerateMD5Hashes, try to take advantage of all the cores available, relying on the work done under the hood by Parallel.For to optimize its behavior according to the existing hardware at runtime.

1. The original GenerateAESKeys subroutine with the sequential For loop, and its parallelized version
  • Original sequential For version (code file: Listing02.sln):
 Sub GenerateAESKeys()
     Dim sw = Stopwatch.StartNew()
     Dim aesM As New AesManaged()
     For i As Integer = 1 To NUM_AES_KEYS ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required