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.
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.
Sub GenerateAESKeys() Dim sw = Stopwatch.StartNew() Dim aesM As New AesManaged() For i As Integer = 1 To NUM_AES_KEYS ...