Seapoe Seapoe - 8 months ago 72
C# Question

MaxDegreeOfParallelism Not Applying to list of Tasks?

I have a list of tasks that I want to execute in parallel but in a limited fashion, almost like batching without me having to manage it. My approach was to use Parallel.ForEach and the MaxDegreeOfParallelism property of ParallelOptions. I'm finding that no matter what I set the value to, all of the tasks start at the same time. This is undesired behavior. I want the amount of tasks that are executing concurrently to be equal to the property. I wrote a simple example for illustration

class Program
static void Main(string[] args)
var numbers = Enumerable.Range(1, 5);
var tasks = new List<Task>();

foreach (int number in numbers)
tasks.Add(new Task(() => {Console.WriteLine("Starting thread {0} at time {1}. Starting delay...", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
Console.WriteLine("{0} is done at {1}.", Thread.CurrentThread.ManagedThreadId, DateTime.Now);}));

Parallel.ForEach(tasks, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, t =>


Here's the output:
Console Output

Is my approach or understanding incorrect?

Answer Source

I think you are a bit confused, the max degree of parallellism is applied to the quantity of tasks used by the parallel ForEach but inside you're creating new tasks, these aren't controlled by the ParallelOptions but by the TaskScheduler.

If you want to limit the number of concurrent tasks you must create a custom TaskScheduler and limit the number of tasks running.

Here you can find an example.