SlideShare a Scribd company logo
1 of 6
Concurrent collections object in DotNet 4.0<br />Today I am going to discuss Concurrent collections which have implicit thread safety features in dotnet 4.0. These are new <br />These are concurrent collections in dotnet 4.0<br />,[object Object]
ConcurrentDictionary<T>: Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
ConcurrentBag<T>: Represents a thread-safe, unordered collection of objects.
BlockingCollection<T>: Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.I’ll also discuss IProducerConsumerCollection<T> interface here which defines methods to manipulate thread-safe collections intended for producer/consumer usage. This interface provides a unified representation for producer/consumer collections so that higher level abstractions such as System.Collections.Concurrent.BlockingCollection<T> can use the collection as the underlying storage mechanism.<br />ConcurrentQueue<T> <br />Represents a thread-safe first in-first out (FIFO) collection. Concurrent Queue removed Dequeue and Peek method; instead it has introduced TryPeek and TryDequeue which ensure safe retrieval of records. It doesn’t use locks at all instead it rely on Interlocked operations to achieve thread-safety.<br />These methods are follows<br />bool TryDequeue<T>(out T result);  attempts to dequeue record from beginning of queue and remove it from queue.<br />bool TryPeek<T>(out T result);  attempts to peek record from beginning of queue without removing it.<br />Below example is showing use of ConcurrentQueue collection object. In this example, first queue is filled up with 1000 records and then “N” method is dequeue records and sum the value<br />class SampleQueue<br />    {<br />        System.Collections.Concurrent.ConcurrentQueue<int> _concurrentQueue = new ConcurrentQueue<int>();<br />        <br />        public void FillQueue()<br />        {<br />            for (int p = 0; p < 1000; p++)<br />                _concurrentQueue.Enqueue(p);<br />            Action action = () =><br />            {<br />                N();<br />            };<br />   // Start 4 concurrent consuming actions.<br />   Parallel.Invoke(action, action,action,action);<br />    Console.WriteLine(quot;
outerSum = {0}, should be 1000quot;
, outerSum);<br />        }<br />   private void N()<br />        {<br />            int localValue;<br />            int localSum = 0;<br />            while (_concurrentQueue.TryDequeue(out localValue)) localSum++;<br />            Console.WriteLine(quot;
Localsum: {0} ThreadID: {1}quot;
, localSum, Thread.CurrentThread.ManagedThreadId);<br />            Interlocked.Add(ref outerSum, localSum);<br />        }<br />Parallel.Invoke(params Action[]  actions)= Execute each of action in parallel, opens up no of thread equal to nbr of processors in computer.<br />ConcurrentDictionary<br />Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.<br />Important Methods<br />GetOrAdd<br />public TValue GetOrAdd(TKey key, TValue value);<br />public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory);<br />Adds a key/value pair to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>. If the key does not already exist.<br />Returns:<br />The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value if the key was not in the dictionary.<br />TryAdd<br />public bool TryAdd(TKey key, TValue value);<br />Attempts to add the specified key and value to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>.<br />Returns:<br />true if the key/value pair was added to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue> successfully; otherwise, false.<br />        <br />public bool TryAdd(TKey key, TValue value);<br />TryGetValue<br />public bool TryGetValue(TKey key, out TValue value);<br />Attempts to get the value associated with the specified key from the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>.<br />Returns:<br />true if the key was found in the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>; otherwise, false.<br />Other methods<br />public bool TryRemove(TKey key, out TValue value);<br />public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue);<br />Example<br />  class SampleDictionary<br />    {<br />        ConcurrentDictionary<int, int> _dictionary = new ConcurrentDictionary<int, int>();<br />        public void FillDictionary()<br />        {<br />            //AddorUpdate Method<br />            _dictionary.AddOrUpdate(1, 2, new Func<int, int, int>(add));<br />            _dictionary.AddOrUpdate(1, 2, new Func<int, int, int>(add));<br />            //GetOrAdd<br />            int result = _dictionary.GetOrAdd(2, 44);<br />            //TryRemove<br />            int val = 0;<br />            _dictionary.TryRemove(1, out val);<br />            //TryUpdate<br />            //bool d= _dictionary.TryUpdate(2,34,55);<br />        }<br />        private int add(int key, int value)<br />        {<br />            return key + value;<br />        }<br />    }<br />ConcurrentBag<T><br />It is new type of collection in dotnet 4.0 which is unordered collection of objects. It’s a kind of bag in which we add and take something.<br />Important Methods<br />Add(T item): This method is use for adding object in collection.<br />Max() : Returns Maximum value from collection.<br />Min():Returns minimum value from collection.<br />TryTake(out T result):  Attempts to remove and return an object from the System.Collections.Concurrent.ConcurrentBag<T>.<br />TryPeek(out T result) : Attempts to return an object from the System.Collections.Concurrent.ConcurrentBag<T> without removing it<br />ConcurrentBag<int> cb = new ConcurrentBag<int>();<br />        cb.Add(1);<br />        cb.Add(2);<br />        cb.Add(3);<br />        // Consume the items in the bag<br />        int item;<br />        while (!cb.IsEmpty)<br />        {<br />            if (cb.TryTake(out item))<br />                Console.WriteLine(item);<br />            else<br />                Console.WriteLine(quot;
TryTake failed for non-empty bagquot;
);<br />        }<br />        // Bag should be empty at this point<br />        if (cb.TryPeek(out item))<br />            Console.WriteLine(quot;
TryPeek succeeded for empty bag!quot;
);<br />    }<br />BlockingCollection<T>:<br />Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>. A blocking collection wraps any collection that implements IProducerConsumerCollection<T> and lets you Take an element from the wrapped collection — blocking if no element is available. You can  also limit total size of collection which blocks producer if that size exceed.<br />Important Methods<br />Add and TryAdd<br />If you call Add method of collection it will block reading operation until adding operation done while TryAdd method is non block adding mechanism.<br />Take and TryTake methods remove items from collection.<br />CompleteAdding<br />This method enforce collection to not add item further.<br />In below code there are two tasks running in parallel, one is adding item and one is removing item from collection and block at Take method to get item. Task.WaitAll method waits for parallel executing tasks to be completed.<br />BlockingCollection<int> bc = new BlockingCollection<int>();<br />            int i = 1;<br />            // Spin up a Task to populate the BlockingCollection <br />            Task t1 = Task.Factory.StartNew(() =><br />            {<br />                while (i != 5)<br />                {<br />                    bc.Add(i);<br />                    Console.WriteLine(quot;
Adding {0} by task1quot;
, i);<br />                    i++;<br />                }<br />               <br />                bc.CompleteAdding();<br />            });<br />            // Spin up a Task to consume the BlockingCollection<br />            Task t2 = Task.Factory.StartNew(() =><br />            {<br />                try<br />                {<br />                    // Consume bc<br />                    while (true) Console.WriteLine(quot;
Getting {0} : Left item :{1}quot;
,bc.Take(),bc.Count);<br />                }<br />                catch (InvalidOperationException)<br />                {<br />                    // IOE means that Take() was called on a completed collection<br />                    Console.WriteLine(quot;
That's All!quot;
);<br />                }<br />            });<br />Task.WaitAll(t1, t2);<br />
Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4

More Related Content

What's hot

Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
seanmcq
 
Mocks introduction
Mocks introductionMocks introduction
Mocks introduction
Sperasoft
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
Technopark
 

What's hot (18)

Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
The Ring programming language version 1.6 book - Part 7 of 189
The Ring programming language version 1.6 book - Part 7 of 189The Ring programming language version 1.6 book - Part 7 of 189
The Ring programming language version 1.6 book - Part 7 of 189
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Reviewing a Complex DataWeave Transformation Use-case
Reviewing a Complex DataWeave Transformation Use-caseReviewing a Complex DataWeave Transformation Use-case
Reviewing a Complex DataWeave Transformation Use-case
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Saving lives with rx java
Saving lives with rx javaSaving lives with rx java
Saving lives with rx java
 
Intro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & ArraysIntro To C++ - Class #18: Vectors & Arrays
Intro To C++ - Class #18: Vectors & Arrays
 
Iron python
Iron pythonIron python
Iron python
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - Collections
 
Mocks introduction
Mocks introductionMocks introduction
Mocks introduction
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with Blocks
 
Theads services
Theads servicesTheads services
Theads services
 

Similar to Concurrent Collections Object In Dot Net 4

I really need help with my C++ assignment. The following is the info.pdf
I really need help with my C++ assignment. The following is the info.pdfI really need help with my C++ assignment. The following is the info.pdf
I really need help with my C++ assignment. The following is the info.pdf
wasemanivytreenrco51
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
julien.ponge
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
sktambifortune
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 PriorityQueue.cs   Jim Mischel using System; using Sy.pdf PriorityQueue.cs   Jim Mischel using System; using Sy.pdf
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
rajat630669
 

Similar to Concurrent Collections Object In Dot Net 4 (20)

I really need help with my C++ assignment. The following is the info.pdf
I really need help with my C++ assignment. The following is the info.pdfI really need help with my C++ assignment. The following is the info.pdf
I really need help with my C++ assignment. The following is the info.pdf
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Tutorial 6 queues & arrays & results recording
Tutorial 6   queues & arrays & results recording Tutorial 6   queues & arrays & results recording
Tutorial 6 queues & arrays & results recording
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 PriorityQueue.cs   Jim Mischel using System; using Sy.pdf PriorityQueue.cs   Jim Mischel using System; using Sy.pdf
PriorityQueue.cs Jim Mischel using System; using Sy.pdf
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 

More from Neeraj Kaushik (12)

How to place orders through FIX Message
How to place orders through FIX MessageHow to place orders through FIX Message
How to place orders through FIX Message
 
Futures_Options
Futures_OptionsFutures_Options
Futures_Options
 
No sql
No sqlNo sql
No sql
 
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specificationImplementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
Implementation of fix messages for fix 5.0 sp2 and fixt1.1 specification
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression Calculator
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using Knockoutjs
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Quick Fix Sample
Quick Fix SampleQuick Fix Sample
Quick Fix Sample
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview Questions
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 

Recently uploaded

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 

Concurrent Collections Object In Dot Net 4

  • 1.
  • 2. ConcurrentDictionary<T>: Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.
  • 3. ConcurrentBag<T>: Represents a thread-safe, unordered collection of objects.
  • 4. BlockingCollection<T>: Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>.I’ll also discuss IProducerConsumerCollection<T> interface here which defines methods to manipulate thread-safe collections intended for producer/consumer usage. This interface provides a unified representation for producer/consumer collections so that higher level abstractions such as System.Collections.Concurrent.BlockingCollection<T> can use the collection as the underlying storage mechanism.<br />ConcurrentQueue<T> <br />Represents a thread-safe first in-first out (FIFO) collection. Concurrent Queue removed Dequeue and Peek method; instead it has introduced TryPeek and TryDequeue which ensure safe retrieval of records. It doesn’t use locks at all instead it rely on Interlocked operations to achieve thread-safety.<br />These methods are follows<br />bool TryDequeue<T>(out T result); attempts to dequeue record from beginning of queue and remove it from queue.<br />bool TryPeek<T>(out T result); attempts to peek record from beginning of queue without removing it.<br />Below example is showing use of ConcurrentQueue collection object. In this example, first queue is filled up with 1000 records and then “N” method is dequeue records and sum the value<br />class SampleQueue<br /> {<br /> System.Collections.Concurrent.ConcurrentQueue<int> _concurrentQueue = new ConcurrentQueue<int>();<br /> <br /> public void FillQueue()<br /> {<br /> for (int p = 0; p < 1000; p++)<br /> _concurrentQueue.Enqueue(p);<br /> Action action = () =><br /> {<br /> N();<br /> };<br /> // Start 4 concurrent consuming actions.<br /> Parallel.Invoke(action, action,action,action);<br /> Console.WriteLine(quot; outerSum = {0}, should be 1000quot; , outerSum);<br /> }<br /> private void N()<br /> {<br /> int localValue;<br /> int localSum = 0;<br /> while (_concurrentQueue.TryDequeue(out localValue)) localSum++;<br /> Console.WriteLine(quot; Localsum: {0} ThreadID: {1}quot; , localSum, Thread.CurrentThread.ManagedThreadId);<br /> Interlocked.Add(ref outerSum, localSum);<br /> }<br />Parallel.Invoke(params Action[] actions)= Execute each of action in parallel, opens up no of thread equal to nbr of processors in computer.<br />ConcurrentDictionary<br />Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.<br />Important Methods<br />GetOrAdd<br />public TValue GetOrAdd(TKey key, TValue value);<br />public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory);<br />Adds a key/value pair to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>. If the key does not already exist.<br />Returns:<br />The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the new value if the key was not in the dictionary.<br />TryAdd<br />public bool TryAdd(TKey key, TValue value);<br />Attempts to add the specified key and value to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>.<br />Returns:<br />true if the key/value pair was added to the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue> successfully; otherwise, false.<br /> <br />public bool TryAdd(TKey key, TValue value);<br />TryGetValue<br />public bool TryGetValue(TKey key, out TValue value);<br />Attempts to get the value associated with the specified key from the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>.<br />Returns:<br />true if the key was found in the System.Collections.Concurrent.ConcurrentDictionary<TKey,TValue>; otherwise, false.<br />Other methods<br />public bool TryRemove(TKey key, out TValue value);<br />public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue);<br />Example<br /> class SampleDictionary<br /> {<br /> ConcurrentDictionary<int, int> _dictionary = new ConcurrentDictionary<int, int>();<br /> public void FillDictionary()<br /> {<br /> //AddorUpdate Method<br /> _dictionary.AddOrUpdate(1, 2, new Func<int, int, int>(add));<br /> _dictionary.AddOrUpdate(1, 2, new Func<int, int, int>(add));<br /> //GetOrAdd<br /> int result = _dictionary.GetOrAdd(2, 44);<br /> //TryRemove<br /> int val = 0;<br /> _dictionary.TryRemove(1, out val);<br /> //TryUpdate<br /> //bool d= _dictionary.TryUpdate(2,34,55);<br /> }<br /> private int add(int key, int value)<br /> {<br /> return key + value;<br /> }<br /> }<br />ConcurrentBag<T><br />It is new type of collection in dotnet 4.0 which is unordered collection of objects. It’s a kind of bag in which we add and take something.<br />Important Methods<br />Add(T item): This method is use for adding object in collection.<br />Max() : Returns Maximum value from collection.<br />Min():Returns minimum value from collection.<br />TryTake(out T result): Attempts to remove and return an object from the System.Collections.Concurrent.ConcurrentBag<T>.<br />TryPeek(out T result) : Attempts to return an object from the System.Collections.Concurrent.ConcurrentBag<T> without removing it<br />ConcurrentBag<int> cb = new ConcurrentBag<int>();<br /> cb.Add(1);<br /> cb.Add(2);<br /> cb.Add(3);<br /> // Consume the items in the bag<br /> int item;<br /> while (!cb.IsEmpty)<br /> {<br /> if (cb.TryTake(out item))<br /> Console.WriteLine(item);<br /> else<br /> Console.WriteLine(quot; TryTake failed for non-empty bagquot; );<br /> }<br /> // Bag should be empty at this point<br /> if (cb.TryPeek(out item))<br /> Console.WriteLine(quot; TryPeek succeeded for empty bag!quot; );<br /> }<br />BlockingCollection<T>:<br />Provides blocking and bounding capabilities for thread-safe collections that implement IProducerConsumerCollection<T>. A blocking collection wraps any collection that implements IProducerConsumerCollection<T> and lets you Take an element from the wrapped collection — blocking if no element is available. You can also limit total size of collection which blocks producer if that size exceed.<br />Important Methods<br />Add and TryAdd<br />If you call Add method of collection it will block reading operation until adding operation done while TryAdd method is non block adding mechanism.<br />Take and TryTake methods remove items from collection.<br />CompleteAdding<br />This method enforce collection to not add item further.<br />In below code there are two tasks running in parallel, one is adding item and one is removing item from collection and block at Take method to get item. Task.WaitAll method waits for parallel executing tasks to be completed.<br />BlockingCollection<int> bc = new BlockingCollection<int>();<br /> int i = 1;<br /> // Spin up a Task to populate the BlockingCollection <br /> Task t1 = Task.Factory.StartNew(() =><br /> {<br /> while (i != 5)<br /> {<br /> bc.Add(i);<br /> Console.WriteLine(quot; Adding {0} by task1quot; , i);<br /> i++;<br /> }<br /> <br /> bc.CompleteAdding();<br /> });<br /> // Spin up a Task to consume the BlockingCollection<br /> Task t2 = Task.Factory.StartNew(() =><br /> {<br /> try<br /> {<br /> // Consume bc<br /> while (true) Console.WriteLine(quot; Getting {0} : Left item :{1}quot; ,bc.Take(),bc.Count);<br /> }<br /> catch (InvalidOperationException)<br /> {<br /> // IOE means that Take() was called on a completed collection<br /> Console.WriteLine(quot; That's All!quot; );<br /> }<br /> });<br />Task.WaitAll(t1, t2);<br />