I'm using a Parallel.ForEach
in my code. All my 8 cores go to 100%. This is bad for the other apps that are running on the server. Is it possible to limit execution to like 4 cores?
We can restrict the number of concurrent threads created during the execution of a parallel loop by using the MaxDegreeOfParallelism property of ParallelOptions class.
maxConcurrency decides how many threads can execute parallelly at the same time, Let's say if it is set to 2 and total records to be processed are 10 then remaining 8 will be queued. For Parallel Foreach, By default (when no maxConcurrency provided), all routes run in parallel.
No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.
Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.
Pass an instance of ParallelOptions
with ParallelOptions.MaxDegreeOfParallelism
set to 4 to Parallel.ForEach
.
Nevertheless this might not make sense on other machines, that might have more or less cores than you. In general you should let the framework decide the degree of parallelism.
You can pass in a ParallelOptions
with the MaxDegreeOfParallelism
property set to 4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With