Supply loop options to parallel loops in .NET C#

It’s possible to supply additional options to parallel for and foreach loops. The ParallelOptions class has the following properties:

  • CancellationToken: sets the cancellation to break a parallel loop
  • MaxDegreeOfParallelism: sets the max concurrency for a parallel loop. A value of -1 means no limit
  • TaskScheduler: this is normally null as the default task scheduler is very efficient. However, if you have a custom task scheduler then you can supply it here

We won’t go into building a custom task scheduler as it is a heavy topic and probably 98% of all .NET programmers are unlikely to ever need one.

So let’s see what MaxDegreeOfParallelism can do for us. It cannot do much directly other than setting a limit to the number of tasks created during a parallel loop. Note the word ‘limit’: setting a high number won’t guarantee that this many Tasks will be started. It is only an upper limit that the task scheduler will take into account. A value of 0, i.e. no concurrency at all, will cause an exception to be thrown in Parallel.For and Parallel.ForEach. A value of 1 is practically equal to sequential execution.

Declare the options object as follows:

ParallelOptions parallelOptions	= new ParallelOptions() { MaxDegreeOfParallelism = 1 };

You can supply the options to the Parallel.For and ForEach methods as input parameters:

Parallel.For(0, 10, parallelOptions, index =>
{
	Console.WriteLine("For Index {0} started", index);
	Thread.Sleep(100);
	Console.WriteLine("For Index {0} finished", index);
});

int[] integers = new int[] { 0, 2, 4, 6, 8 };

Parallel.ForEach(integers, parallelOptions, index =>
{
	Console.WriteLine("ForEach Index {0} started", index);
	Thread.Sleep(100);
	Console.WriteLine("ForEach Index {0} finished", index);
});

Run the code an you should see that the index values are processed in a sequential manner. Then set MaxDegreeOfParallelism to e.g. 5 and you should see something different.

View the list of posts on the Task Parallel Library here.

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.