The CLR’s thread pool

        1. What is the CLR’s thread pool?

        2. How does the CLR’s thread pool manage threads?

        3. How does the CLR’s thread pool clean up resources?

        4. What are the worker threads?

        5. What are the I/O threads?

The CLR’s thread pool is a set of threads available to use for your application. There is only one thread pool per the CLR. This thread pool is shared by all AppDomains controlled by that CLR.

When the CLR initialized, the thread pool has no threads in it. Internally the thread pool is a queue of operation requests. When an application needs to perform an asynchronous operation it puts an entry in the threads pool queue. The CLR’s thread pool tries to handle the request in its queue using available threads. If there are no available threads the thread pool creates a new thread. When a thread pool’s thread completes its work this thread is not destroyed it returns back to the threads pool and sits idle.

If the thread pool sits idle for some period of time the thread pool starts destroying the idle threads and clean ups resources.

Internally, the tread pool categorizes threads as either worker threads or I/O threads. The worker threads are used when your application performs asynchronous compute-bound operations. The I/O threads are used when we need to handle events generated by asynchronous I/O operations.

Sample 1:

    class Program

    {

        static void Main(string[] args)

        {

            Trace.WriteLine(“Main thread: Queuing an asynchronous compute-bound operation”);

            ThreadPool.QueueUserWorkItem(ComputeBoundOp, “ThreadPool: Performing an asynchronous operation”);

            Trace.WriteLine(“Main thread: Let’s give a chance to start an aasynchronous operation “);

            Thread.Sleep(10000);

            Trace.WriteLine(“Main thread: Waiting until user press Enter”);

            Console.ReadKey();

        }

        private static void ComputeBoundOp(Object state)

        {

            Trace.WriteLine((string) state);

            Thread.Sleep(10000);

        }

    }

Output:

Main thread: Queuing an asynchronous compute-bound operation

Main thread: Let’s give a chance to start an aasynchronous operation

ThreadPool: Performing an asynchronous operation

Main thread: Waiting until user press Enter

The thread ‘<No Name>’ (0x294) has exited with code 0 (0x0).

The thread ‘<No Name>’ (0x11b0) has exited with code 0 (0x0).