should we use MaxDegreeOfParallelism option when use Parallel.For RRS feed

  • Question

  • it is good to use MaxDegreeOfParallelism option when use Parallel.For ?

    class Program
        static void Main(string[] args)
            var locker = new Object();
            int count = 0;
                 , 1000
                 , new ParallelOptions { MaxDegreeOfParallelism = 2 }
                 , (i) =>
                           Interlocked.Increment(ref count);
                           lock (locker)
                               Console.WriteLine("Number of active threads:" + count);
                            Interlocked.Decrement(ref count);

    why the above program use Interlocked.Increment(ref count); ?

    if they do not use Interlocked.Increment() then what worse may happen ?

    please guide me. thanks

    Friday, December 21, 2018 7:29 AM


  • No. The Parallel class will already "optimally" parallelize your code based upon what is available and the work involved. So setting the property isn't necessary. The only times you would do so is for testing purposes or if you need to limit the amount of parallelism because of limitations in the worker code (e.g. making multiple calls to the same HTTP endpoint).

    The reason Interlocked is being used is because they want to show you how many threads are being used. To do that each thread needs to increment a shared value (count). Changing a variable on different threads at the same time will lead to bad results. Threads have to run in isolation. To allow multiple threads to change the same data you have to use synchronization. This will often involve semaphores, mutexes or locks. In the special case of a couple of primitive types (ints, longs, ref types) then the CPU has an atomic operation that can be used instead. That is what Interlocked is for. An interlock increment using the CPU to atomically (and thread safely) increment a shared value. The CPU guarantees it is changed once and that no other thread will collide with this. It is the most efficient way to increment/decrement/swap some primitives. In all other cases you'll upgrade to a sync object.

    Note the code you posted is strictly for example purposes and should not be taken as the correct way to do things. It is not common to need to use interlocked in code. If your code is so interdependent that you need to use sync objects then maybe you need to reconsider your architecture and/or not do parallel at all. Synchronization can get tricky to implement and hard to debug/verify. It is available when needed, not to be used every time.

    Michael Taylor

    • Marked as answer by Sudip_inn Friday, December 21, 2018 9:16 PM
    Friday, December 21, 2018 3:09 PM