Reputation: 2072
In my application I have a number of classes that can compute their tasks using Parallel.For
statement. Each Parallel.For
uses its own ParallelOption
that sets a maximum degree of parallelism.
The application flow is dependent on a user setup so there are situations like: class A (which computes in parallel) calls class B (that also computes in parallel) or it calls class C (that is not using any parallel computing).
Another pattern is recursive calls where on each level of recursion a parallel computation is done.
My questions:
Is it possible to setup a global thread pool that is used by all classes to do its calculatins, and the numer of threads is controlled globally for application?
Is it possible to combine thread pool with Parallel.For
so most of the existing code stays unchanged?
How much overhead puts a thread pool compared to independend parallel.for calls (I know that it all depends, ad by the end I need to do some testing, but maybe you have some good and bad expirence and good advices)
Upvotes: 2
Views: 2061
Reputation: 10873
Parallel.For
will use all the thread pool threads by default, and the number of thread pool threads is optimized for your cpu(s). MaxDegreeOfParallelism
is only useful if you want to not use all of the thread pool threads for a given loop.
Just use Parallel.For
and don't overthink it.
Later on, if your app really requires it, you can still create your own TaskScheduler
with your own thread pool... but it's very improbable that you actually need to do that.
Upvotes: 0
Reputation: 15217
Is it possible to setup a global thread pool that is used by all classes to do its calculatins, and the numer of threads is controlled globally for application?
This is already the case. Currently, the application thread pool is managed by the .NET runtime. So you can be pretty sure, that all your classes (in a running application) use the same thread pool. You can access the thread pool either by using Task
s, the static ThreadPool
class or the static Parallel
class.
Is it possible to combine thread pool with Parallel.For so most of the existing code stays unchanged?
Parallel.For
internally uses Tasks
and the TaskScheduler
. So, the same thread pool will be used.
Upvotes: 2