Powered by Blogger.

Saturday, March 1, 2014

Concurrent Collections in .NET 4.0:

Concurrent Collections are the key of Parallel programming introduced in .NET 4.0. It is included in the System.Collections.Concurrent namespace.

Also check out:

- List all Stored Procedure Created and Modified in Last N Days in SQL Server 2008

- Simple JavaScript textbox validation example in Asp.Net

- Working with enterprise library for data access in asp.net Part-1

Why we need Concurrent Collections?
Collections in .NET are not Thread safe and Generics introduced in .NET 2.0 are type safe but not Thread safe.

Generics allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code.

But Generics are not Thread safe, it’s  programmer’s responsibility. For example you have a list    collecting some objects. If the  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, when  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. The Concurrent collections allow us to share the data amongst several threads without any worry.The new classes for the concurrency in Concurrent collections are:
ConcurrentQueue <t>-  Thread-safe version of a queue (FIFO).
ConcurrentStack <t>-  Thread-safe version of a stack (LIFO).
ConcurrentBag<t> - Thread-safe unordered collection of objects.

- Optimized for situations where a thread may be bother reader and writer.

ConcurrentDictionary < Key , Value>
- Thread-safe version of a dictionary.
- Optimized for multiple readers (allows multiple readers under same lock).
BlockingCollection<t>-  Wrapper collection that implement producers & consumers paradigm.
- Readers can block until items are available to read.
- Writers can block until space is available to write (if bounded).

 Benefits of  Concurrent collections:

- Programmer  need not 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.

 ConcurrentDictionary < Key , Value> : It  is commonly used list.
- 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.

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;

class c1
    static ConcurrentDictionary< int, string >  cd =new ConcurrentDictionary< int, string >();

    static void Main()
Thread t1 = new Thread(new ThreadStart(m1));
Thread t2 = new Thread(new ThreadStart(m2));


    static void m1()
for (int i = 0; i <= 100; i++)
   cd.TryAdd(i,”m1 added”+ i);
    static void m2()
for (int i = 0; i < =100; i++)
   cd.TryAdd(i,”m2 added”+ i);