Friday 20 November 2015

Thread Pooling in C#


Thread pooling is the process of creating a collection of threads during the initialization of a multi-threaded application, and then reusing those threads for new tasks as and when required, instead of creating new threads.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

With thread pooling, you call the ThreadPool.QueueUserWorkItem method with a delegate for the procedure you want to run, and Visual Basic or C# creates the thread and runs your procedure.


How to Assign Thread in ThreadPool ?

ThreadPool.QueueUserWorkItem(new WaitCallback(FunctionCall), PersonalizeDataForTherad);


The first parameter specifies the function that we want to execute on the pool. Its signature must match the delegate WaitCallback.


There are some important methods of ThreadPool class which are given below:

GetType:- It is used to obtain the type for the current thread pool.

Equals:- It is used to determine whether two thread pool are equal or not.

SetMaxThreads:-It is used ,to specify the number of requests to the ThreadPool that can be concurrently active.

SetMinThreads:-It is used to specify the number of idle threads that can be maintained by a   thread pool for new requests.

QueueuserWorkItem:-It allows a method to be queued for execution.


Example :

using System;
using System.Threading;
namespace Poolthread
{
class student
{
static object newthread = new object();
static int i = 10;
public static void Main(string[] args)
{
for (int j = 0; j < i; j++)
{
ThreadPool.QueueUserWorkItem(show, j);
Console.WriteLine("10 threads are running one by one and stop after 5 second");

lock (newthread)
{
if(i > j)
Monitor.Wait(newthread);
}
}
Console.WriteLine("Threads are stopped successfully");
Console.ReadLine();
}
public static void show(object newobj)
{
Console.WriteLine("Thread started:"+newobj);
Thread.Sleep(5000);
Console.WriteLine("Thread ended:"+newobj);
lock(newthread)
{
Monitor.Pulse(newthread);
}
}
}

}

Output:

Thread started 0
10 threads are running one by one and stop after 5 second
Thread ended 0
Thread started 1
10 threads are running one by one and stop after 5 second
Thread ended 1
Thread started 2
10 threads are running one by one and stop after 5 second
Thread ended 2
Thread started 3
10 threads are running one by one and stop after 5 second
Thread ended 3
Thread started 4
10 threads are running one by one and stop after 5 second
Thread ended 4
….
….
….
….
….

This will run for thread 9
Threads are stopped successfully.




No comments:

Post a Comment