Skip to Content
Professional Visual Basic 2012 and .NET 4.5 Programming
book

Professional Visual Basic 2012 and .NET 4.5 Programming

by Bill Sheldon, Billy Hollis, Rob Windsor, David McCarter, Gastón Hillar, Todd Herman
January 2013
Intermediate to advanced
912 pages
26h 58m
English
Wrox
Content preview from Professional Visual Basic 2012 and .NET 4.5 Programming

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Visual Basic 2012 Programmer's Reference

Visual Basic 2012 Programmer's Reference

Rod Stephens

Publisher Resources

ISBN: 9781118332139Purchase book