If you have worked with Threads you should know that create threads can be an expensive task. If your application needs to create different threads, your code will need something smarter than just start threads to avoid that overhead.
Today let’s check the code to use the .NET Thread Pool that consists in a smart thread manager that creates an initial number of threads and after receive requests from the client application will start to assign tasks for the live threads. If your application requests more threads than the number of threads available on the Thread Pool the CLR will create new threads to perform the tasks. On the other hand, if threads have been suspended for some time, the threads and the resources associated to them will be released.
The simplest way to use the Thread Pool is using one of the QueueUserWorkItem method overloads. The method is static and may be invoked from the ThreadPool object.
The following code snippet enqueues a call to a method named MyCallback. The method should expect an object as parameter:
static void Main(string args)
/// Enqueue one call and set up the callback method
static void MyCallback(Object stateInfo)
Console.WriteLine(“Called from the thread pool”);
I am going to publish during the next week, different ways to use the ThreadPool.