- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make your collections thread-safe in C#
The .NET Framework 4 brought the System.Collections.Concurrent namespace. This has several collection classes that are thread-safe and scalable. These collections are called concurrent collections because they can be accessed by multiple threads at a time.
The following concurrent collection types use lightweight synchronization mechanisms: SpinLock, SpinWait, etc. These are new in .NET Framework 4.
Let us see the concurrent collection in C# −
Type | Description |
---|---|
BlockingCollection<T> | Bounding and blocking functionality for any type. |
ConcurrentDictionary<TKey,TValue> | Thread-safe implementation of a dictionary of key-value pairs. |
ConcurrentQueue<T> | Thread-safe implementation of a FIFO (first-in, first-out) queue. |
ConcurrentStack<T> | Thread-safe implementation of a LIFO (last-in, first-out) stack. |
ConcurrentBag<T> | Thread-safe implementation of an unordered collection of elements. |
IProducerConsumerCollection<T> | The interface that a type must implement to be used in a BlockingCollection |
Let us see how to work with ConcurrentStack<T> that is a thread-safe last in-first out (LIFO) collection −
ConcurrentStack<int> cs = new ConcurrentStack<int>(); cs.Push(95); cs.Push(120); cs.Push(130);
Advertisements