In this code snippet, we will take a look at thread pools in .NET and C#.
Creating threads and disposing of them when a task is done can be an expensive operation to perform as it uses up time and memory. To mitigate this we can use a thread pool which is essentially a collection of pre instantiated threads. We can assign tasks to these threads. When the task is completed the thread gets returned to the thread pool instead of being disposed of.
- When you initialize the class you would create some threads and put them in the thread queue.
- Then you would add some tasks to your task queue.
- While tasks are present in the task queue you would keep dequeuing them. For each of the dequeued tasks, you would dequeue a thread and assign it that task.
- When the thread completes the task it then gets queued back into the thread queue thus keeping a reference to it and prevent it from being destroyed by the garbage collector.
However, making your own thread pool is really not advisable as you would just be complicating your life for no reason. Microsoft already made a thread pool in .NET that you can use(and it’s very easy). In this post, I will show how to use the said thread pool.
At the end of the day, you should just use the TPL(Task Parallel Library) which is a library made specifically to make multithreading/parallel/asynchronous code execution easier. The TPL already uses a thread pool behind the scenes.
Let’s have a look at the code below to see how to use the thread pool.