A thread pool is a collection of threads that can be used to perform several tasks in the background. This leaves the primary thread free to perform other tasks asynchronously. put in queue until they can be serviced as threads become available.
There are a number of ways you can enter the thread pool:
Here I will discuss ThreadPool.QueueUserWorkItem only. In my next article I will discuss other ways.
One advantage of thread pooling is that you can pass arguments in a state object to the task procedure. If the procedure you are calling requires more than one argument, you can cast a structure or an instance of a class into an Object data type. It is similar to ParameterizedThreadStart.
using System;
using System.Threading;
namespace TestConsole
{
class Program
{
public static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(DoLongTask); //Without passing input parameter
ThreadPool.QueueUserWorkItem(DoLongTask, "Hello"); //With input parameter
Console.WriteLine("Main thread ends");
Console.ReadKey();
}
public static void DoLongTask(object input)
{
Console.WriteLine("Thread is background : {0}", Thread.CurrentThread.IsBackground);
Console.WriteLine("Input parameter : {0}", input);
}
}
}
You should not use Sleep() or Join() methods if you are using ThreadPool. It may cause some unexpected behaviour. TheardPool’s threads are meant to complete the tasks as soon as possible without sleeping and in background.
You must explicitly deal with exceptions in the target code — un-handled exceptions will take down the program.
Asynchronous Delegates
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)