Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Thread managed by the thread pool?

Tags:

c#

clr

threadpool

I know that the CLR gives each AppDomain ThreadPool time slice to work , yet i wanted to know if by creating a new thread like so Thread t = new Thread(...);

Is it managed by the CLR or by the AppDomin ThreadPool ?

like image 506
guyl Avatar asked Dec 21 '22 08:12

guyl


2 Answers

Thread t = new Thread(); will not be managed by the ThreadPool. But it is an abstraction provided by the CLR on the Operating System threads. ThreadPool is an addtional abstraction which facilitates reusing threads and sharing thread resources.

Here is an excellent resource on threads in .NET: http://www.albahari.com/threading/

If you're using .NET 4.0 consider using TPL.

like image 136
rtalbot Avatar answered Dec 24 '22 01:12

rtalbot


When you create threads with the Thread class, you are in control. You create them as you need them, and you define whether they are background or foreground (keeps the calling process alive), you set their Priority, you start and stop them.

With ThreadPool or Task (which use the ThreadPool behind the scenes) you let the ThreadPool class manage the creation of threads, and maximizes reusability of threads, which saves you the time needed to create a new thread. One thing to notice is that unlike the Thread default, threads created by the ThreadPool don't keep the calling process alive.

A huge advantage of using the ThreadPool is that you can have a small number of threads handle lots of tasks. Conversely, given that the pool doesn't kill threads (because it's designed for reusability), if you had a bunch of threads created by the ThreadPool, but later the number of items shrinks, the ThreadPool idles a lot, wasting resources.

like image 20
Gustavo Mori Avatar answered Dec 24 '22 00:12

Gustavo Mori