What is the difference between:
- Starting a new thread
- Using TPL
- Using BackgroundWorker
All of these create concurrency but what are the low-level differences between these? Do all 3 make threads anyway?
Thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They all use threads internally, the differences are to do with the abstraction level of each API and how the threads are utilised. Lets re-order your list a bit and look at the three techniques from lowest to highest levels of abstraction:
Starting a new thread manually:
This actually creates a new thread in the OS. Your code will be executed on that thread.
Using a BackgroundWorker:
Internally this uses something called the .net ThreadPool. The thread pool is basically a pool of available threads. Your code is assigned onto one of the available threads and is run on that thread.
The pool manages the number of available threads and will internally create and destroy threads as required within certain bounds. This is useful because the pool can have some algorithms to optimise thread creation. Thread creation is quite an expensive process, so if appropriate the thread pool keep threads alive and reuse them for future requests. You can have some limited control over the pool by specifying min/max numbers of threads and some minor tweaks like that.
There are other ways of using the ThreadPool directly such as QueueUserWorkItem(…).
Using the Task Parallel Library:
This is an even higher abstraction. You create “tasks” and tell the TPL to execute them. The TPL hides all the concerns regarding exactly how many threads and what priorities will be used etc. The TPL has the ability to reuse threads and manage them according to specific machine performance and available CPU resources.
For example given 100 tasks, on a Quad core the TPL might spawn 4 threads, but on an 8 core it might spawn 8 and distribute the tasks over the available threads as each task completes.
So to answer you question. All 3 techniques use threads, but as you go up each level the amount of control and awareness you have over those threads is reduced.
In most cases, I would recommend you use the TPL. Unless you need specific very exact control over the number of threads and their creation/destruction the TPL will handle it all very well for you.