Click here to Skip to main content
15,884,739 members
Articles / General Programming / Threads
Tip/Trick

Controlled ThreadPool using .NET Framework 4.0

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
8 Nov 2011CPOL 24.1K   6   8
How to do controlled ThreadPooling using .NET Framework 4.0.

Introduction


Controlled ThreadPool using BlockingCollection in .NET Framework 4.0.


Background


A very common requirement is to create a pool of defined number of threads and execute tasks on it. For years, We have been controlling the tasks queue collection using locks and having all threads running all the time even when there are no tasks in queue. Another way is to use ManualResetEvents as explained here nicely: http://blogs.msdn.com/b/pfxteam/archive/2010/04/13/9995622.aspx.


Recently I came across the new Threading class (BlockingCollection) available in .NET Framework 4.0 and found that now we can do the same job without locks and without running threads all the time. Also it require less line of neat code.


Using the code


This class is written using generics which means it can store any type of task and one handler for those tasks. It can also be used as a collection for multiple handlers.


C#
public class OrderlyThreadPool<t> : IDisposable
{
    BlockingCollection<t> _workingqueue = null;
    Action<t> _handler = null;
    public OrderlyThreadPool(int wrkerCount, Action<t> handler)
    {
        _workingqueue = new BlockingCollection<t>();
        _handler = handler;
        Worker worker = new Worker(wrkerCount, Process);
        worker.Start();
    }

    public void AddItem(T item)
    {
        _workingqueue.Add(item);
    }
    private void Process()
    {
        foreach (T item in _workingqueue.GetConsumingEnumerable())
        {
            _handler(item);
        }
    }
    public void Dispose() { _workingqueue.CompleteAdding(); 
                            _workingqueue = null; }

}
/*
 * Class which handles the workers on the queue 
 */
public class Worker
{
    int _wrkerCount = 0;
    Action _action = null;
    public Worker(int workerCount, Action action)
    {
        _wrkerCount = workerCount;
        _action = action;

    }
    public void Start()
    {
        // Create and start a separate Task for each consumer:
        for (int i = 0; i < _wrkerCount; i++)
        {
            Task.Factory.StartNew(_action);
        }
    }
}

Caller:


C#
static void main()
{
   OrderlyThreadPool<city> threadpool = new OrderlyThreadPool<city>(6, new Action<city>(Handler));
                threadpool.AddItem(new City() { CityZipCode = "60661",CityName ="Chicago",State="Illinois" });
}
static void Handler(City c)
{
   Console.WriteLine(c.CityName);	
   Console.WriteLine(c.CityZipCode);
   Console.WriteLine(c.State);
}

class City
{
    public string CityName;
    public string CityZipCode;
    public string State;
}
</city></city></city>

Note: This class requires reference to System.Collections.Concurrent,System.Threading.Tasks and System.Collections.Generic
namespaces.


Points of Interest


Threading has been improved significantly with many new classes like LocalThread.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Bank of America Merrill Lynch
United States United States
Software developer with 7 years of experience in MS technologies. Also love to write code using open source like python,java.

Comments and Discussions

 
GeneralCity???- what is wrong??? Pin
j_alles8-Nov-11 9:19
j_alles8-Nov-11 9:19 
GeneralRe: j_alles, Thanks for bringing in notice the Caller code. I h... Pin
manish313838-Nov-11 13:49
manish313838-Nov-11 13:49 
Generalfor some reason <City> does not print out-----????? Pin
j_alles8-Nov-11 9:18
j_alles8-Nov-11 9:18 
GeneralThe <City> was not printing out: It should be--> OrderlyThr... Pin
j_alles8-Nov-11 9:18
j_alles8-Nov-11 9:18 
GeneralSorry, This should be the line in Main(): OrderlyThreadPo... Pin
j_alles8-Nov-11 9:16
j_alles8-Nov-11 9:16 
General---> I had to make the following changes to get your code wo... Pin
j_alles8-Nov-11 9:12
j_alles8-Nov-11 9:12 
QuestionPass additional data to each thread Pin
Omar Al Zabir8-Nov-11 3:35
Omar Al Zabir8-Nov-11 3:35 
AnswerRe: Pass additional data to each thread Pin
manish313838-Nov-11 13:31
manish313838-Nov-11 13:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.