Specifying the Desired Degree of Parallelism

TPL methods always try to achieve the best results using all the available logical cores. Sometimes, however, you don't want to use all the available cores in a parallel loop, either because you have specific needs, and therefore better plans for the remaining available cores, or you want to leave one core free to create a responsive application and the remaining core can help you run another part of code in parallel. In these cases, you want to specify the maximum degree of parallelism for a parallel loop.

ParallelOptions

TPL enables you to specify a different maximum desired degree of parallelism by creating an instance of the new ParallelOptions class and changing the value of its MaxDegreeOfParallelism property. The code in file Listing 12.sln shows a new version of the two well-known subroutines that use Parallel.For, ParallelGenerateAESKeysMaxDegree, and ParallelGenerateMD5HashesMaxDegree.

Now, they receive an Integer with the maximum desired degree of parallelism, maxDegree. Each subroutine creates a local instance of ParallelOptions and assigns the value received as a parameter to its MaxDegreeOfParallelism property, which is a new parameter for each parallel loop before the body. This way, the loop won't be optimized to take advantage of all the available cores (MaxDegreeOfParallelism = -1). Instead, it will be optimized as if the total number of available cores were equal to the maximum degree of parallelism specified in the ...

Get Professional Visual Basic 2012 and .NET 4.5 Programming 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.