Click here to Skip to main content
Click here to Skip to main content

Controlled ThreadPool using .NET Framework 4.0

, 8 Nov 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

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:

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)

Share

About the Author

manish31383
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??? Pinmemberj_alles8-Nov-11 10:19 
GeneralRe: j_alles, Thanks for bringing in notice the Caller code. I h... Pinmembermanish313838-Nov-11 14:49 
Generalfor some reason <City> does not print out-----????? Pinmemberj_alles8-Nov-11 10:18 
GeneralThe <City> was not printing out: It should be--> OrderlyThr... Pinmemberj_alles8-Nov-11 10:18 
GeneralSorry, This should be the line in Main(): OrderlyThreadPo... Pinmemberj_alles8-Nov-11 10:16 
General---> I had to make the following changes to get your code wo... Pinmemberj_alles8-Nov-11 10:12 
QuestionPass additional data to each thread PinmvpOmar Al Zabir8-Nov-11 4:35 
AnswerRe: Pass additional data to each thread Pinmembermanish313838-Nov-11 14:31 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 8 Nov 2011
Article Copyright 2011 by manish31383
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid