Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tasks vs ThreadPool

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.

like image 408
prestomanifesto Avatar asked Nov 09 '11 21:11

prestomanifesto


People also ask

Does task use ThreadPool?

By default, TPL types like Task and Task<TResult> use thread pool threads to run tasks. You can also use the thread pool by calling ThreadPool.

When should you not use ThreadPool?

Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.

What is difference between thread and task?

A thread is one of the many possible workers which performs that task. In . NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.

Should I use task or thread?

It is always advised to use tasks instead of thread as it is created on the thread pool which has already system created threads to improve the performance. The task can return a result. There is no direct mechanism to return the result from a thread.


1 Answers

Please take a look at ParallelOptions.MaxDegreeOfParallelism for Tasks.

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 :)

like image 98
Vladislav Zorov Avatar answered Sep 22 '22 16:09

Vladislav Zorov