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

Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
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 189Mahmoud Samir Fayed
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
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-caseAlexandra N. Martinez
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
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 & ArraysBlue Elephant Consulting
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
C++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsC++ Windows Forms L07 - Collections
C++ Windows Forms L07 - CollectionsMohammad Shaker
 
Mocks introduction
Mocks introductionMocks introduction
Mocks introductionSperasoft
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutinesNAVER Engineering
 
iOS Development with Blocks
iOS Development with BlocksiOS Development with Blocks
iOS Development with BlocksJeff Kelley
 

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.pdfwasemanivytreenrco51
 
Stack Implementation
Stack ImplementationStack Implementation
Stack ImplementationZidny Nafan
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Tutorial 6 queues & arrays & results recording
Tutorial 6   queues & arrays & results recording Tutorial 6   queues & arrays & results recording
Tutorial 6 queues & arrays & results recording Mohd Batati
 
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++nsm.nikhil
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
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.pdfsktambifortune
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 
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#Juan Pablo
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
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.pdfrajat630669
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 

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

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 MessageNeeraj Kaushik
 
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 specificationNeeraj Kaushik
 
C-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorC-Sharp Arithmatic Expression Calculator
C-Sharp Arithmatic Expression CalculatorNeeraj Kaushik
 
Implement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsImplement Search Screen Using Knockoutjs
Implement Search Screen Using KnockoutjsNeeraj Kaushik
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
DotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsDotNet &amp; Sql Server Interview Questions
DotNet &amp; Sql Server Interview QuestionsNeeraj Kaushik
 

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

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

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 />