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

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 ...

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