Thread Pooling in C# with example

 

Introduction

In this article document we will try to a very important concept called thread pooling in c#. Kindly note : Before reading this article we recommend to read our previous article i.e What is Threading and Types of Threading using a simple example in C# to read this article See Here.

In our previous document we have seen how to create threading, we learned about threading, implemented threading and implemented types of threading. Here we will go into next step and learn ThreadPooling C#. Now in order to understand thread pooling we will first understand concept of thread pooling, thread object life cycle and benchmarks between Thread Pooling and Thread Class using a real time example.

What is Thread Pooling in C# ?

In order to understand thread pooling first we will understand about thread life cycle, what exactly happens when a create a thread of a multithreaded application.

Thread Life Cycle

When a framework receives request call i.e method or function it creates thread object when a thread object is created it gets allocated with some memory resources after that method or function is executed or task executed then after this execution finally garbage collections removes that object to free some memory.

So first request calls then thread object creates then memory resources allocated then task executed then finally goes to garbage collection to free some memory.

Friends..this is how a Thread Life Cycle is been executed on .NET framework.

If you look at the above thread life cycle you can notice that for every thread object request the same steps are repeated again and again in a multithreaded environment. These steps can consume lots of memory space and CPU usage and can make our application a bit slow. Now to over come these by saving our memory usage and cpu processes we can implement thread pooling in our project.

Definition : Thread pooling is a process of creating one or more threads or collection of threads during initialization of a multithreaded environment and then instead of going it to a garbage collection it directly adds it to thread pool for reusability og those threads for same task or new task.

First time when a thread object is been created with some memory allocation to perform some task instead of sending that object to a garbage collector we will add that object to a thread pool. We can do this for a one or more threads. So next time when we want to use any thread object instead of creating a new thread object we can directly use it from a thread pool for reusing it for same task or a new task.

So in simple words what will happen now is for every request call on .net framework it will go to the thread pool and checks for free available threads and from that pool it will use it for executing some task. An image snapshot as shown below.

Friends..! As you saw from above image that biggest advantage of using thread pool is that creation and memory allocation is done only once while creating a new thread and this saves lots of time, cpu usage and memory. Thread Pool leads to large performance gains.

How to implement thread pooling

In this step we will see how to implement thread pooling in the projects but since this is an article document (for simple understanding) so will demonstrate using console application.

Let's create a console application and import the threading system name-space. In the next step create a simple static function called "Run()" and add some coding to it. Here below sample code we have looped it to 27 times using for loop.

 

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

        static void Run(object callback)
        {
            for (int i = 0; i <= 27; i++)
            {
                Console.WriteLine("Number : " + i);
                Thread.Sleep(240);
            }
        }
    }

Now rather than creating a thread object and adding it to a function "Run" we will create a thread pool i.e ThreadPool.QueueUserWorkItem which Queues method for execution and the method executes when a thread thread becomes available to execute.

ThreadPool.QueueUserWorkItem takes overloaded waitcallback function we create a object waitcallback and inside the waitcallback we will pass our custom function "Run()" since waitcallback needs a call back object for call backs we have added that call-back object to our method "Run(object callback)".

The complete source code is shown below.

 

 class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(Run));
            Console.ReadLine();
        }

        static void Run(object callback)
        {
            for (int i = 0; i <= 27; i++)
            {
                Console.WriteLine("Number : " + i);
                Thread.Sleep(240);
            }
        }
    }

Output :

Performance benchmarks between Thread Object and Thread Pool using real time example

Now to perform performance benchmarks between Thread Object and Thread Pool we will first go ahead and create a console application and import threading namespace.

In the next step let's create static empty function called "Run()" with input as object callback as shown in below snippet of code.

 

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

       
        static void Run(object callback)
        {
           
        }   
    }

In next further step let's create a two funtions called as "RunWithThreadPool" and "RunWithoutThreadPool". Inside this functions we will first create loop for 10 times.

 

	  static void RunWithThreadPool()
        {
            for (int i = 0; i <= 10; i++)
            {
               
            }
        }

        static void RunWithOutThreadPool()
        {
            for (int i = 0; i <= 10; i++)
            {
                
            }
        }

Now inside the for-loop of both functions let's add thread pool method in "RunWithThreadPool" function and in "RunWithOutThreadPool" function let's create a thread object and both of these functions i.e. Thread Pool and Thread object will call the same function called "Run()".

 

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

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

In the next step let's call both of these functions in the main method as shown in below snippet of code.

 

        static void Main(string[] args)
        {

            RunWithThreadPool();
            RunWithOutThreadPool();
    
        }

Before executing this code let's add stopwatch to calculate time consumption of a each method and to ensure not to consider the compile time let's call both of these methods once or twice before calling the stopwatch as shown in below sample code.

 

        static void Main(string[] args)
        {
		
		//You call these code once or twice
            RunWithThreadPool();
            RunWithOutThreadPool();


            Stopwatch mywatch = new Stopwatch();

            Console.WriteLine("Run with thread pool");

            mywatch.Start();
            RunWithThreadPool();
            mywatch.Stop();

            Console.WriteLine("Time consumed with thread pool is : "+mywatch.ElapsedTicks.ToString());
            mywatch.Reset();


            Console.WriteLine("Run without thread pool");

            mywatch.Start();
            RunWithOutThreadPool();
            mywatch.Stop();

            Console.WriteLine("Time consumed with out thread pool is : " + mywatch.ElapsedTicks.ToString());
        }

Comple source code is shown below :

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

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

            RunWithThreadPool();
            RunWithOutThreadPool();


            Stopwatch mywatch = new Stopwatch();

            Console.WriteLine("Run with thread pool");

            mywatch.Start();
            RunWithThreadPool();
            mywatch.Stop();

            Console.WriteLine("Time consumed with thread pool is : "+mywatch.ElapsedTicks.ToString());
            mywatch.Reset();


            Console.WriteLine("Run without thread pool");

            mywatch.Start();
            RunWithOutThreadPool();
            mywatch.Stop();

            Console.WriteLine("Time consumed with out thread pool is : " + mywatch.ElapsedTicks.ToString());
        }

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

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

        static void Run(object callback)
        {
           
        }

        
    }
}

Final step is to run this above to check the performance benchmarks between thread pool and thread object.

Display output is shown below.

Conclusion : As you see from display output. Time consumed with thread pool to execute any function it took 25664 ElapsedTicks and Time consumed without thread pool i.e. using thread object to execute any function it took 2785520 ElapsedTicks. So our performance benchmarks says that thread pool gives better performance than thread class object. So if you are looking to implement threading in your application use thread pooling over thread class. But if priority is not about the performance then better use thread class to keep the code simple.

That's all folks about threading in the next upcoming article document we will try to cover (Threading) Mutex, Semaphore and SemaphoreSlim with real time scenario. If you like this article dont forget to give your thumbs up/ share in Facebook, google+.Kindly share it with your friends.Thank you...!

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Oct
06
2014

Step by Step Partial Classes and Partial Methods in C#.NET with example

CLICK TO READ FULL ARTICLE

Views - 8589 |Category - C#

Sep
16
2014

Understand threading and types of threading in c# using an example

CLICK TO READ FULL ARTICLE

Views - 14517 |Category - C#

Aug
24
2014

Understand difference between Early Binding and Late Binding with an example in C#

CLICK TO READ FULL ARTICLE

Views - 23513 |Category - C#

Aug
10
2014

Complete Tutorial on C# 3.0 VAR Keyword with example

CLICK TO READ FULL ARTICLE

Views - 6711 |Category - C#

Aug
07
2014

Complete Tutorial on Dynamic Keyword in C# 4.0 with an example

CLICK TO READ FULL ARTICLE

Views - 8216 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

0fo1r