Parallel.for () loop creating invalid thread IDs

I developed a .net application using the .net framework 4.0, where I used the parallel.for () loop for multithreading. I used the following configuration:

  • Windows 7
  • IIS 7.0
  • Framework v4.0.30319

I used the ParallelOptions () class, and the MaxDegreeOfParallelism property of this class is set to 5. I registered the Thread.CurrentThread.ManagedThreadId file in the log file to check if 5 threads were created at runtime. I tested this application in two different environments. When the application runs in the environment where it was developed, 5 stream identifiers are created. But while it works in a different environment, it creates 6 or 7 thread identifiers. The application is compiled only in the 1st environment. I used the published version of the application for testing in the second environment. Can someone help me by telling why this is happening and how to solve it?

+4
source share
2 answers

Parallel.For uses thread pool threads. MaxDegreeOfParallelism controls the maximum number of simultaneous threads, not 5 specific threads - the thread pool is free to handle work on any of its threads, and Parallel.For ensures that only 5 are executed.

+4
source

I believe this is because Parallel.For() uses only a dynamic delimiter, so the one passed to the array can be partitioned on the fly, and each section is processed by a separate task / thread:

  • MSDN: A Practical Guide. Implementing dynamic partitions

    Each time a section calls MoveNext in an enumerator, the enumerator provides a section with one list item. In the case of PLINQ and ForEach, the section is an instance of the task. Because requests execute multiple threads at the same time, access to the current index is synchronized.

    (I believe the same is true for Parallel.For() )

  • MSDN: custom delimiters

    PLINQ supports a fixed number of partitions (although data can be dynamically reassigned for these partitions during load balancing.). For and ForEach only support dynamic partitioning, which means that the number of sections changes at runtime. For more information, see Custom Separators for PLINQ and TPL.

+2
source

All Articles