By default, parallel LINQ will try to take advantage of all of the processor cores offered by your CPU. Usually, this is what you want. However, there could be situations where you want to limit the number of threads used to run queries and keep some cores available for other work.
In this recipe, we are going to create a query that uses the WithDegreeOfParallelism
method to explicitly set the number of threads that a parallel query uses.
Now, let's see how to limit the degree of parallelism of a query.
Start a new project using the C# Console Application project template, and assign
LimitParallelism
as the Solution name.Add the following
using
directives to the top of yourProgram
class:using System; using System.Linq; using System.Threading;
Let's add a PLINQ query to the
Main
method of theProgram
class that works the processors. For now, we will use theWithExecutionMode
method to force the query to run in parallel, but will not set a limit on...