Reputation: 12796
I have an application in C# with a list of work to do. I'm looking to do as much of that work as possible in parallel. However I need to be able to control the maximum amount of parallel tasks.
From what I understand this is possible with a ThreadPool or with Tasks. Is there an difference in which one I use? My main concern is being able to control how many threads are active at one time.
Upvotes: 9
Views: 15470
Reputation: 3111
You can also create a semaphore to control how many threads can execute at a single time. You can create a new semaphore and in the constructor, specify how many simultaneous threads are able to use that semaphore at a single time. Since I don't know how you are going to be using the threads, this would be a good starting point.
MSDN Article on the Semaphore class
Upvotes: 2
Reputation: 7584
In TPL you can use the WithDegreeOfParallelism
on a ParallelEnumerable
or ParallelOptions.MaxDegreeOfParallism
There is also the CountdownEvent
which may be a better option if you are just using custom threads or tasks.
In the ThreadPool
, when you use SetMaxThreads
its global for the AppDomain
so you could potentially be limiting unrelated code unnecessarily.
You cannot set the number of worker threads or the number of I/O completion threads to a number smaller than the number of processors in the computer.
If the common language runtime is hosted, for example by Internet Information Services (IIS) or SQL Server, the host can limit or prevent changes to the thread pool size.
Use caution when changing the maximum number of threads in the thread pool. While your code might benefit, the changes might have an adverse effect on code libraries you use.
Setting the thread pool size too large can cause performance problems. If too many threads are executing at the same time, the task switching overhead becomes a significant factor.
I agree with the other answer that you should use TPL over the ThreadPool
as its a better abstraction of multi-threading, but its possible to accomplish what you want in both.
Upvotes: 4
Reputation: 12458
Task have a very charming feature to me, you can build chains of tasks. Which are executed on certain results of the task before. A feature I often use is following: Task A is running in background to do some long running work. I chain Task B after it, only executing when Task A has finished regulary and I configure it to run in the foreground, so I can easily update my controls with the result of long running Task A.
Upvotes: 3
Reputation: 3046
Please take a look at ParallelOptions.MaxDegreeOfParallelism for Task
s.
I would advise you to use Tasks, because they provide a higher level abstraction than the ThreadPool.
A very good read on the topic can be found here. Really, a must-have book and it's free on top of that :)
Upvotes: 19