Thread Safe Concurrent Collection in C#

Concurrent Collection

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 are the concurrent collection in C# āˆ’

Sr.No Type & Description
1 BlockingCollection<T>

Bounding and blocking functionality for any type.

2 ConcurrentDictionary<TKey,TValue>

Thread-safe implementation of a dictionary of key-value pairs.

3 ConcurrentQueue<T>

Thread-safe implementation of a FIFO (first-in, first-out) queue.

4 ConcurrentStack<T>

Thread-safe implementation of a LIFO (last-in, first-out) stack.

5 ConcurrentBag<T>

Thread-safe implementation of an unordered collection of elements.

6 IProducerConsumerCollection<T>

The interface that a type must implement to be used in a BlockingCollection

Example

using System;
using System.Collections.Concurrent;

class Demo
{
    static void Main ()
    {
        ConcurrentStack<int> s = new ConcurrentStack<int>();

        s.Push(50);
        s.Push(100);
        s.Push(150);
        s.Push(200);
        s.Push(250);
        s.Push(300);
   
    }
}

Source : https://www.tutorialspoint.com/Thread-Safe-Concurrent-Collection-in-Chash

Author:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.