Click here to Skip to main content
15,115,960 members
Articles / Programming Languages / C#
Technical Blog
Posted 17 Jan 2011

Tagged as


17 bookmarked

Concurrent Collections with .NET 4.0

Rate me:
Please Sign up or sign in to vote.
4.80/5 (13 votes)
17 Jan 2011CPOL2 min read
Concurrent Collections with .NET 4.0

Earlier we used Collections, they were never thread safe. Generics introduced in .NET 2.0 are TypeSafe but not ThreadSafe.

Generics are TypeSafe means whenever you are going to declare any generic type, you need to specify the type that is going to be held by the List. And whenever you are going to retrieve any item from list, you will get the actual type item, not an Object like we get from ArrayList.

But Generics are not ThreadSafe, it’s a programmer’s responsibility. Means let’s say if you have a list collecting some objects. That list is shared amongst several threads, then it may work hazardously if two threads try to access the List at the same point of time, like adding/removing/iterating items from the same list at the same time.

Thread safety can be implemented with the help of locking the collection and other similar ways. But locking the entire list for the sake of adding/removing an item could be a big performance hit for an application based on the circumstances.

.NET 4.0 provides new classes for the concurrency as Concurrent collections. These are:

  • ConcurrentDictionary< Key , Value>: Thread safe dictionary in key value pairs
  • ConcurrentQueue<T>: Thread safe FIFO data structure
  • ConcurrentStack<T>:Thread safe LIFO data structure
  • ConcurrentBag<T>: Thread safe implementation of an unordered collection
  • BlockingCollection<T>: Provides a Classical Producer Consumer pattern

All the above classes are available in the namespace System.Collections.Concurrent.

These collections allow us to share the data amongst several threads without any worry.

Concurrent Collections are the key of Parallel programming, that is introduced in .NET 4.0.

So let’s discuss the very commonly used list ConcurrentDictionary.

  • A thread safe add/remove from dictionary.
  • Very user friendly methods that make it unnecessary for code to check if a key exists before add/remove.
  • AddOrUpdate: Adds a new entry if doesn’t exist else updates existing one
  • GetOrAdd: Retrieves an item if exists, else first adds it then retrieves it
  • TryAdd, TryGetValue,TryUpdate, TryRemove: Allows to do the specified operation like Add/Get/Update/Remove and if it fails, then does the alternative action.

Benefits of the above Concurrent collections:

  • Now programmer doesn’t need to take care of thread safety.
  • Uses light weight synchronization like SpinWait, SpinLock, etc. that use spinning before putting threads to wait – for short wait periods, spinning is less expensive than wait which involves kernel transition.
  • Means faster add/remove/iterate in multithreading environment without writing the code for it.
  • Some other classes like ConcurrentQueue & ConcurrentStack don’t rely on Interlocked operations instead of locks which make them faster.

There is lot more to discuss on this. But keeping it short and simple, let’s finish. We’ll discuss other things in subsequent posts.


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


About the Author

Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.

He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.

He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website

He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.

Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.

Visit his Blog: Code Wala

Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008

Comments and Discussions

Questionwhere is concurrentList(of T) Pin
Marco Bosco22-Nov-13 8:40
MemberMarco Bosco22-Nov-13 8:40 
GeneralMy vote of 1 Pin
Tanveer Ahmad110-Jan-13 18:34
MemberTanveer Ahmad110-Jan-13 18:34 
GeneralMy vote of 5 Pin
Russell Lear24-Jan-11 13:51
MemberRussell Lear24-Jan-11 13:51 
GeneralRe: My vote of 5 Pin
Brij24-Jan-11 21:50
mentorBrij24-Jan-11 21:50 
GeneralMy vote of 5 Pin
Sudeep35020-Jan-11 0:19
MemberSudeep35020-Jan-11 0:19 
GeneralRe: My vote of 5 Pin
Brij24-Jan-11 21:50
mentorBrij24-Jan-11 21:50 

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.