Mar Mosh
Mar Mosh

Reputation: 275

C# TPL for loop - limit number of threads

I want to use only 2 threads to make for loop. I tried this code:

ParallelOptions po = new ParallelOptions {
    MaxDegreeOfParallelism = 2
};

Parallel.For(0, width, po, x => {
    sb.Append(Thread.CurrentThread.ManagedThreadId);
    sb.Append(Environment.NewLine);
    for (int y = 0; y < height; y++) {
        double a = (double)(x - (width / 2)) / (double)(width / 4);
        double b = (double)(y - (height / 2)) / (double)(height / 4);
    }
});

But when I display Thread.CurrentThread.ManagedThreadId, it creates more than 2 ids. I also tried add this code before loop:

ThreadPool.SetMaxThreads(2, 2);
ThreadPool.SetMinThreads(2, 2);

But it also doesn't change anything. Somebody have maybe any idea how can I sovle this problem?

Upvotes: 1

Views: 1434

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109567

The MaxDegreeOfParallelism sets the maximum number of simultaneous threads that will be used for the Parallel.For(). It does not mean that only two threads will ever be used.

Different threads can be allocated from the threadpool during execution of the Parallel.For(), since threadpool threads are specifically designed to be reused.

The following program demonstrates. If you run it, you'll see that the total number of different threads being used can exceed 2, but the total number of threads being used simultaneously never exceeds 2.

using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main()
        {
            ParallelOptions po = new ParallelOptions
            {
                MaxDegreeOfParallelism = 2
            };

            var activeThreads = new ConcurrentDictionary<int, bool>();

            Parallel.For(0, 100, po, x =>
            {
                activeThreads[Thread.CurrentThread.ManagedThreadId] = true;
                Console.WriteLine("Active threads: " + string.Join(", ", activeThreads.Keys));
                Thread.Sleep(200);
                activeThreads.TryRemove(Thread.CurrentThread.ManagedThreadId, out bool unused);
            });

            Console.ReadLine();
        }
    }
}

Upvotes: 2

Related Questions