Home > DeveloperSection > Blogs > ThreadPool class in C#

ThreadPool class in C#


C# C# 
Ratings:
0 Comment(s)
 5203  View(s)
Rate this:

ThreadPool class in C#

ThreadPool class is used to manage a set of readily available threads to be used by a process. We can use ThreadPool class for creating threads when we require large number of short living threads. A short living thread is a thread that is created to perform a single task and then terminated.We can use ThreadPool class when it is not necessary to have full control over each individual threads.

Note: There is a limit of 25 threads in a thread pool. That means if you start 50 threads then only 25 threads is active at a time. As soon as a thread finishes another thread is active from thread pool.

Avoiding uses of ThreadPool class when following situation raise

1.       Requires a foreground thread.

2.       Requires a thread to have a particular priority.

3.       Have task that can block threads for long period of time. The thread pool has a maximum number of threads, so a large number of threads from the thread pool being blocked might prevent task from starting.

4.       Need to have stable identity associated with thread.

5.       Need to place threads into a single threaded apartment.

Implementation of ThreadPool class

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

namespace ThreadStartDemo

{

    class ThreadPoolClassDemo

    {

        static void Main(string[] args)

        {

            //Call QueueUserWorkItem method of ThreadPool claas

            //to send Thread in ThreadPool and pass object of

            //WaitCallback deleaget.

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

            Console.WriteLine("Main Thread Started.");

            Thread.Sleep(10000);

            Console.WriteLine("Main Thread Exists.");

        }

        /// <summary>

        /// This method is passed to WaitCallback delegate.

        /// This method is used to print numbers from 1 to 50.

        /// Main thread exists in two case either time fiven in main sleep

        /// method over of number is printed from 1 to 50.

        /// </summary>

        /// <param name="stateInfo"></param>

        static void ThreadProc(object stateInfo)

        {

            Console.WriteLine("Welcome from thread pool. I will count from 1 to 50");

            for (int i = 1; i <= 50; i++)

            {

                Console.WriteLine(i);

                Thread.Sleep(500);

            }

        }

    }

}

Execute above program to see the output.


Don't want to miss updates? Please click the below button!

Follow MindStick