C# Thread Pooling using example step by step

Introduction

Hello friends, welcome to another day of session to learn csharp step by step. In this tutorial article we will learn about thread pooling in c# using real time scenario step by step.

This article is bit advance version of threading so if you have landed here directly then I would like to request you to read our previous article on Threading and Types of Threading, Here you will understand how to create thread objects and different types of thread methods but if you know threading and particularly looking for this article then continue reading this article.

About us

LearnCsharpTutorial is an initiative started by Questpond to spread C# knowledge to everyone. This website dedicated only to CSharp. Here you can get our self-made videos, articles and learning program details. Any details on C#.NET feel free to contact us, details are mentioned below.

We offer One-to-One trainings on C# and other different techs @ starting from 15000/-

One-to-Many (Group Trainings) starting from @6000 /- only.

We do provide self learning materials like 1000 videos of DVD (Based on MVC, C#, AngularJS, OOPS, SQL Server and many more) sample videos are available on Youtube and our C# Video Section Page.

About Author

My self Gurunatha Dogi an author behind this article and other articles posted on this site, We do have bunch of dedicated teaching staff who day-n-night work for us to make Videos, articles, blogs, Take trainings and to make self learning materials . It's a small team but very dedicated to e-learning zone and to provide you best quality step by step teaching service.

Thread Lifecycle

Before we go and understand thread pooling let's understand life cycle of thread, When a .NET framework receives request of a method call then it creates new thread object which gets allocated on memory and then it executes task. Once the task gets complete then garbage collector removes that thread object for free-up memory allocation. So this life cycle of a thread.

So for every time for every new request a framework creates a new thread object which get allocated on memory. If there are many request then there will be many thread objects, if there are many thread objects for every task then there will be load on memory and thus makes an application slow.

To over comes this problem when there are situation to create to many thread objects instead of going with standard method of thread creation, best to go with thread pooling.

So hope you understand requirement of thread pooling on .NET framework and Life cycle of a thread.

Thread Pooling in Csharp

Thread pool is a collection of threads which can be used to perform no of task in background. Once thread completes its task then it sent to the pool to a queue of waiting threads, where it can be reused. This reusability avoids an application to create more threads and this enables less memory consumption.

Once task is completed in thread pool, .NET framework sends these task completed threads to thread pool rather than sending these threads to garbage collector. Further which can be reused for other new task.

After the first time initialization On .NET Framework, if there are new method calls then Framework go to thread pool and automatically assign task to free available threads.

So this is a benefit of working with thread pool which enable less memory consumption for large number of task.

Steps to Create Thread Pooling in C#.NET

Step 1

So to implement thread pooling in an application we need use Threading namespace as shown in below code.


using System.Threading;

Step 2

After using threading namespace we need to call threadpool class, using threadpool object we need to call method i.e. "QueueUserWorkItem" - which Queues function for an execution and a function executes when a thread becomes available from thread pool.

ThreadPool.QueueUserWorkItem takes overloaded method called waitcallback - Represents a callback function to be executed by a thread pool thread. If no thread is available it will wait until one gets freed.


ThreadPool.QueueUserWorkItem(new WaitCallback(Run));

Here Run() is the method to be executed by a thread pool thread

Step 3

In this step we will compare how much time does thread object takes and how much time does thread pool takes to executes any methods. For the same we will create a two methods called ProcessWithThreadMethod() and ProcessWithThreadPoolMethod() and inside that we will create a 10 times loop. These two methods will call a simple method called "Process()" which has got input object as a parameter since waitcallback needs an input parameter for callbacks.


static void Process(object callback)
{

}

As you see this is just an empty method and this method will be called by two methods to execute.

Step 4

Let's create two methods one by one


static void ProcessWithThreadMethod()
{
      for (int i = 0; i <= 10; i++)
	  {
	        Thread obj = new Thread(Process);
	        obj.Start();
	  }
}


static void ProcessWithThreadPoolMethod()
{
      for (int i = 0; i <= 10; i++)
	  {
	        ThreadPool.QueueUserWorkItem(new WaitCallback(Process));
	  }
}

Step 5

Our main part is ready now just we need to call these methods to our main method, Since we are testing time consumption so we will call these methods between stopwatch start and end. This is final step so we will provide complete code.


 

using System;
using System.Threading;
using System.Diagnostics;

namespace ThreadPooling
{
     class Program
    {
        static void Main(string[] args)
        {

            
            Stopwatch mywatch = new Stopwatch();

            Console.WriteLine("Thread Pool Execution");

            mywatch.Start();
            ProcessWithThreadPoolMethod();
            mywatch.Stop();

            Console.WriteLine("Time consumed by ProcessWithThreadPoolMethod is : " + mywatch.ElapsedTicks.ToString());
            mywatch.Reset();


            Console.WriteLine("Thread Execution");

            mywatch.Start();
            ProcessWithThreadMethod();
            mywatch.Stop();

            Console.WriteLine("Time consumed by ProcessWithThreadMethod is : " + mywatch.ElapsedTicks.ToString());
        }

        static void ProcessWithThreadPoolMethod()
        {
            for (int i = 0; i <= 10; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(Process));
            }
        }

        static void ProcessWithThreadMethod()
        {
            for (int i = 0; i <= 10; i++)
            {
                Thread obj = new Thread(Process);
                obj.Start();
            }
        }

        static void Process(object callback)
        {

        }


    }
}



Display output is shown below :

Conclusion :

So if you see above output which shows Time consumed by ProcessWithThreadPoolMethod is 1356 and Time consumed by ProcessWithThreadMethod is 16964 so if you see there is a vast difference between time consumption and memory consumption.

So our practicle solution says that thread pool gives better performance over thread class object. If there are one or two threads needs to be used for multitask environment use Thread class object if there are more than 5 threads needs to be used then go for thread pool class.

Hope you have enjoyed reading this article session if you find this article is useful then kindly share it with your friends on social networks and spread knowledge as much as possible.

+91-9769000232
+91 9967590707
questpond@questpond.com / questpond@yahoo.com
Mobile : +91-9967590707, Stay tuned with us and get all LIVE training updates, new/upcoming topic video info from QuestPond with our new Telegram Channel, just install Telegram app & subscribe using this link t.me/questpond