Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to limit the cores for Parallel.ForEach?

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?

like image 583
Kees C. Bakker Avatar asked Apr 01 '11 10:04

Kees C. Bakker


People also ask

How do I limit the number of threads in parallel ForEach?

We can restrict the number of concurrent threads created during the execution of a parallel loop by using the MaxDegreeOfParallelism property of ParallelOptions class.

What is Max concurrency in parallel ForEach?

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.

Is parallel ForEach blocking?

No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.

Does parallel ForEach use ThreadPool?

Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.


2 Answers

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.

like image 122
Florian Greinacher Avatar answered Sep 25 '22 06:09

Florian Greinacher


You can pass in a ParallelOptions with the MaxDegreeOfParallelism property set to 4.

like image 36
Jon Skeet Avatar answered Sep 22 '22 06:09

Jon Skeet