ThreadPool

I discovered this class the other day.  It’s actually been around for a while as part of the .NET 2.0 framework.  You can use it to run a method in a different thread.  Here’s a description from the MSDN site.

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

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.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here’s a very simple example that illustrates how the main execution thread continues without waiting for the “DoSomething” thread to complete.  ≈

    class ThreadPoolExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), args);

            Console.WriteLine("Finish");

            Console.ReadLine();
        }

        private static void DoSomething(object args)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }

Here’s the output:

 

 

 

 

 

 

If we needed to know when the work was finished from Threadpool, then a ManualResetEvent could be passed into a WaitHandle like the example described here.

Advertisements

About Brian McKay
Software Architect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: