This is due to how the internal Parallel.ForEach balancer works. When he sees that your threads spend a lot of time blocking, he explains that he can speed up the process by throwing more problems into the problem, which will lead to increased parallel overhead, competition for your FileLock and overall performance degradation.
Why is this happening? Since Parallel.ForEach not designed to work with IO.
How can you fix this? Use Parallel.ForEach only for CPU operation and perform all I / O operations outside of the parallel loop.
A quick workaround is to limit the number of Parallel.ForEach threads allowed to enlist using the overload that takes ParallelOptions , for example:
Parallel.ForEach( System.IO.File.ReadLines(inputFile), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, (line, _, lineNumber) => { ... }
source share