Working with Concurrent Collections in .NET Framework 4.0

Concurrent collections in .NET Framework 4.0 allow the developers to create type safe as well as thread safe collections. These collection classes form an essential part of the parallel programming feature and are available under the namespace System.Collections.Concurrent. Below are the different types of concurrent collections.

1. ConcurrentDictionary<TKey, TValue>
2. ConcurrentStack<T>
3. ConcurrentQueue<T>
4. ConcurrentBag<T>
5. BlockingCollection<T>

The producer and consumer pattern can easily be implemented while using ConcurrentStack, ConcurrentQueue and ConcurrentBag as they implement the interface IProducerConsumerCollection.

Need for Concurrent Collections

Though System.Collections namespace offers a wide range of collections, the only thing which limits our use of them in a multi-threaded or parallel environment is that they are not thread-safe. A non thread-safe collection will lead to race conditions and throw unexpected exceptions. In order to make them thread safe, a locking mechanism should be implemented as shown in the example below.

Dictionary<string, string> _dictionaryCollection = new Dictionary<string, string>();
object _lockingObject = new object();
public void AddToCollection(string key, string value)
{
            lock (_lockingObject)
            {
                _dictionaryCollection.Add(key, value);
            }
}
 

The above code will work fine in a multi-threaded operation but it is a little costly in terms of performance, since it blocks all the other threads until the current thread exits the lock. This is why concurrent collections are required. Concurrent collections can be shared across multiple threads with no explicit locks and it also increases the scalability and performance of multi-threaded operations.

ConcurrentDictionary

ConcurrentDictionary is used to create a thread-safe key value pair. It offers several methods, such as TryAdd, TryGetValue, AddOrUpdate, etc. All these methods are thread-safe. Below is the sample code for using ConcurrentDictionary.

class Program
{
 
    static void Main(string[] args)
    {
        //Consider this as a list from database which is huge and we need to represent this data as a keyvalue pair using ConcurrentDictionary
        string[] techWebSites = new string[] { "www.codeguru.com", "www.internet.com", "www.devx.com", "www.developer.com" };
 
        Task[] taskList = new Task[2];
 
        ConcurrentDictionary<int, string> dictionaryWebsites = new ConcurrentDictionary<int, string>();
 
        //With the creation of two tasks we have divided the load of populating the collection byt without doing any explicit synchronization
        taskList[0] = Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < techWebSites.Length; i++)
                {
                    if (dictionaryWebsites.TryAdd(i, techWebSites[i]))
                        Console.WriteLine("Website {0} added to the dictionary!", techWebSites[0]);
                }
            });
 
        taskList[1] = Task.Factory.StartNew(() =>
        {
            for (int i = 0; i < techWebSites.Length; i++)
            {
                if (dictionaryWebsites.TryAdd(i, techWebSites[i]))
                    Console.WriteLine("Website {0} added to the dictionary!", techWebSites[0]);
            }
        });
 
        Task.WaitAll();
 
    }
}

ConcurrentQueue

ConcurrentQueue is a thread-safe first in first out (FIFO) collection. The code below is using ConcurrentQueue in a multi-threaded operation.

class Program
{
    static void Main(string[] args)
    {
        ConcurrentQueue<string> nameCollection = new ConcurrentQueue<string>();
        nameCollection.Enqueue("Adam Hollioke");
        nameCollection.Enqueue("Ben Hollioke");
        nameCollection.Enqueue("Ronie Irani");
        nameCollection.Enqueue("Patrick");
        nameCollection.Enqueue("Stuart Clarke");
        nameCollection.Enqueue("Mike Gatting");
 
        Task[] taskList = new Task[2];
 
        taskList[0] = Task.Factory.StartNew(() =>
            {
                string name = String.Empty;
                while (nameCollection.TryDequeue(out name))
                    Console.WriteLine("Name {0} is dequeued!", name);
            });
 
        taskList[1] = Task.Factory.StartNew(() =>
        {
            string name = String.Empty;
            while (nameCollection.TryDequeue(out name))
                Console.WriteLine("Name {0} is dequeued!", name);
        });
 
        Task.WaitAll();
        Console.ReadLine();
    }
}

ConcurrentStack

ConcurrentStack is a thread-safe collection to perform last in first out (LIFO) operations. The code below demonstrates the use of ConcurrentStack.

class Program
{
    static void Main(string[] args)
    {
        ConcurrentStack<int> numberCollection = new ConcurrentStack<int>();
        for (int i = 10; i <= 20; i++)
        {
            numberCollection.Push(i);
        }
 
        Parallel.For(0, 10, i =>
            {
                int value = 0;
                if (numberCollection.TryPop(out value))
                    Console.WriteLine("Value {0} is popped out!", value);
            });
 
        Console.ReadLine();
    }
}

A range of values can be pushed into or popped out from the ConcurrentStack using the methods PushRange and TryPopRange.

ConcurrentBag

ConcurrentBag is used to maintain the list of unordered items. TryTake and TryPeek methods can be used it take the item out of the bag and to peek for the value in the bag respectively. Below is the sample code to use ConcurrentBag.

class Program
{
    static ConcurrentBag<string> _entityCollection = new ConcurrentBag<string>();
    static void Main(string[] args)
    {
        _entityCollection.Add("Company1");
        _entityCollection.Add("Catalog1");
        _entityCollection.Add("Order1");
        _entityCollection.Add("Company2");
        _entityCollection.Add("Catalog2");
        _entityCollection.Add("Order2");
        _entityCollection.Add("Company3");
        _entityCollection.Add("Catalog3");
        _entityCollection.Add("Order3");
 
        ThreadStart threadStart = new ThreadStart(PrintEntities);
        Thread thread1 = new Thread(threadStart);
        thread1.Start();
        Thread thread2 = new Thread(threadStart);
        thread2.Start();
 
        Console.ReadLine();
    }
 
    static void PrintEntities()
    {
        string entity = String.Empty;
        while (_entityCollection.TryPeek(out entity))
        {
            if (_entityCollection.TryTake(out entity))
                Console.WriteLine(entity);
        }
    }
}

BlockingCollection

BlockingCollection is the perfect candidate for implementing the producer and consumer pattern over a thread-safe collection. The producer and consumer pattern generally spawns two threads where one thread adds the data to the collection and at the same time the collection would be consumed by the other. BlockingCollection takes care of blocking the threads until a vacant space is available in the collection while adding and until a data is added to the collection while consuming. I will cover the BlockingCollection in more detail in a future article.

I hope this article provided enough insight about concurrent collections in .NET Framework 4.0. Happy Reading!



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There Offer the cheap MBT shoes online with good quality 5d

    Posted by Rxabkmu82 on 03/19/2013 01:56am

    [p]Mulberry Bags Are Famous For The Excellent Design Even so, for these designer [url=http://www.burberrycoatsales.com]burberry jacket[/url] mulberry men's bags bag and other components, women of all ages have a very smart number of money Evo Leger . The pattern of donning handbags has by no means been out of [url=http://www.burberrycoatsales.com]burberry shoes[/url] the trend scene . Mulberry Outletis situated in ChilCompton, with [url=http://www.burberry520.com]burberry discount[/url] 190 expert employees and 10 production lines . As you may recognise, some varieties of latest approach approaches and movements will change when a new time of the year is upcoming . Just now, since his disenchantment with farming was Mulberry bags 2012 glad to stay with Apart from the fact UK Mulberry Outlet Shop Bags the sight of Cheap Mulberry Bags Sale Handbags happy and affectionate couple, so pleased with themselves and everyone else, and their well-ordered home, had always a cheering effect on he felt a longing, now UK Mulberry Outlet Shop Bags he was so dissatisfied with his own life, to get at UK Mulberry Outlet Shop Bags secret in which gave him [url=http://www.burberrycoatsales.com]burberry coat[/url] such clarity, definiteness, and good courage in life . Reputable mulberry handbags for target Mulberry accoutrements ability fee as continued as lots of money . Quite a few hundreds of many years ahead with the starting with all the twentieth century, [url=http://www.lovelyburberry.com]burberry sale[/url] hand bags were designed absent from mulberry bags prevalent materials found inside the people's locality . It appealed to greater extent to women and turned out as the biggest hit amongst other Mulberry bags.[/p][p]This bag easily converts from a modern, slouchy tote bag with short leather handles 篓C to a super feminine messenger style bag with zip drawing a line under . Every single lovely person really should get one . It was found in 1970 by Roger Saul . The 2011 Newest Style Mulberry Bags Release As everybody, we can see such an excellent brand or luckily possess a Mulberry 2011 but we are rarely aware of the complete method of designing a Mulberry [url=http://www.lovelyburberry.com]burberry handbags[/url] bag . Mulberry Outlet illustrates Rydon Homes隆炉 commitment to excellence and the provision of homes that are outstanding places to live and investments [url=http://www.burberry520.com]burberry outlet online[/url] that provide peace of mind . As you may recognise, some varieties of latest approach approaches and movements will change when a new time of the year is upcoming . You needn't go out of house, just need [url=http://www.burberrycoatsales.com]burberry shirt[/url] open you company search online and place the order, the products you bought will be sent to your address . The new Bayswater is beautiful during this bright red version, I have found perfect diamond necklace to a new thousand outfits, such may be the bag to put on along with a total white or total black look after which it be blended with accessories and red lipstick, for instance, belt, shoes , purse and lipstick red, as being a little provocative, but the form, sometimes you might want to see transgressive and sexy around the mirror.[/p]

    Reply
  • Good Article.

    Posted by Nilesh on 10/15/2012 09:16pm

    Good Article. i help me a lot.

    Reply
  • good

    Posted by anitha on 08/20/2012 04:57am

    your article is good and the way explanation also good. can i get your email id so i can ask few more doubts which i am having

    Reply
  • Not readable

    Posted by Luis on 05/08/2012 01:10am

    I like the article and how you explain it, but this website makes the code very unreadable in the way its posted.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Businesses are moving more and more of their customer transactions to the web. Security is understandably a top concern as online transactions increase, so it is important to make sure your electronic signature provider meets the highest security standards. That means more than simply passing a security audit or obtaining a certification. This white paper provides recommendations for taking a broader view of e-signature security, and answers key questions that help identify the security requirements against …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds