ThreadPool

ThreadPool is an interesting concept and entirely different from the earlier approach. In fact, a collection of threads is created based on the system resources (like memory) availability. By default, the thread pool has 25 threads per processor.

On demand, thread pool size can be scaled up and down to match the code execution.  Every thread of ThreadPool is always associated with a specific given task. On completion, the underlying thread will return to the pool manager for further assignments. It has been depicted in the following diagram:

In terms of implementation, the System.Threading.ThreadPool class handles the creation of new threads along with the efficient distribution of consumer and management among those threads.

Though there are a number of ways to create thread pool in C#, the simplest way is by calling ThreadPool.QueueUserWorkItem.

This method allows us to launch the execution of a function on the system thread pool. Its declaration is as follows:

    ThreadPool.QueueUserWorkItem(new WaitCallback(Consume));

The first parameter specifies the function that we want to execute on the pool. Framework expects to match the delegate of WaitCallback, as follows:

    public delegate void WaitCallback(object state);

In terms of implementation, here is a simple example to illustrate the ThreadPool concept in .NET C# code:

    using System;
using System.Threading;

namespace PacktThreadSample
{
class ThreadPoolTest
{
static void Main()
{
Console.WriteLine("Before handover to ThreadPool..");
System.Threading.ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkerThread), "Content insider Worker
Thread");

Console.WriteLine("Right after ThreadPool retrun..");
// Give the callback wait time of 2 mins after
WorkerThread trigger
// Else App might terminate before the control returns
Thread.Sleep(2000);
Console.WriteLine("2 minutes dealy after
ThreadPool retrun..");
}
static void WorkerThread (object parameter)
{
Console.WriteLine(parameter);
}
}
}

The only catch in ThreadPool is to handle the asynchronous thread execution. As the best practice, the main thread needs to await for the complete worker thread execution.  On executing the preceding C# ThreadPool code, the result will be as follows:

Technically, thread pooling is essential in multithreaded enterprise applications for response time improvement, thread management, optimized thread timing, and more.

ThreadPool can only run so many jobs at once, and some framework classes use it internally, so you do not want to block it with many tasks that need to block for other things.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.74.232