[C#] Multithreading in C# 3 [6] – ThreadPool

Creating and destroying a thread can be an expensive operation. For better performance, you can make use of a thread pool. You can queue the task to the pool and the runtime will figure out how to create or reuse a thread in the pool.

1. ThreadPool Class

The “System.Threading.ThreadPool” class is a static class that provides the access to a pool of threads that can be used to post work items.

public static class ThreadPool
{
  public static bool QueueUserWorkItem(WaitCallback callBack);
  public static bool QueueUserWorkItem(WaitCallback callBack, Object state);
}

By providing callback delegate, you can safely start a new thread.

2. WaitCallback Delegate

WaitCallback” is a simple delegate type.

public delegate void WaitCallback(Object state);

3. Queuing the Work Item

It is pretty easy to use the ThreadPool.

public class RangeParameter
{
  public int Start { get; set; }
  public int End { get; set; }
}

public static class ThreadPoolTest
{
  public static void Test1()
  {
    RangeParameter range = new RangeParameter { Start = 10, End = 50 };

    ThreadPool.QueueUserWorkItem(state =>
      {
        RangeParameter data = state as RangeParameter;
        for (int i = data.Start; i < data.End; i++)
        {
          Console.Write(i + " ");
          Thread.Sleep(1);
        }
      },
      range
    );

    for (int j = 0; j < 10; j++)
    {
      Console.Write("- ");
      Thread.Sleep(1);
    }
  }
}

When you run this code, you can see that all numbers from 10 to 49 will not be printed. Why? By default, ThreadPool creates the background thread.

4. Pros and Cons of ThreadPool Threads

Pros:

  • The thread pool manages threads efficiently

Cons:

  • Pooled threads are always background threads with default priority (ThreadPriority.Normal).

Therefore if you need a foreground thread, you need to create it manually using the “Thread” class.

 

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s