c sharp

What is C# Concurrent List

It is typical in concurrent programming to have numerous threads accessing and making changes to the same data. As a result, thread safety becomes a crucial factor to ensure data consistency and prevent data corruption. This is where concurrent collections come in handy. Concurrent lists are one such collection in C# that are designed to be accessed and modified by multiple threads simultaneously without any conflicts or data corruption. In this article, we will dive into what a concurrent list is, and how to use it in C# with the help of an example.

What is Concurrent List in C#

Concurrent lists are thread-safe collections in C# that allow several threads to use them concurrently without the requirement for external synchronization. This means that multiple threads can read and write to the list concurrently without causing conflicts or data corruption.

Syntax for Concurrent List in C#

To use a concurrent list in C#, you need to include the System.Collections.Concurrent namespace and instantiate a ConcurrentBag<T> object, where T is the type of elements that the list will contain. A concurrent list can be created using the syntax shown below:

using System.Collections.Concurrent;

ConcurrentBag<T> list = new ConcurrentBag<T>();

Here, ConcurrentBag<T> is the class that represents the concurrent list, and T is the type of elements that the list will contain. You can add or remove items from the list using the Add and TryTake methods, respectively.

Using Concurrent List in C#

Let’s say you want to create a program that generates a list of random numbers and sorts them concurrently using multiple threads. Here’s how a concurrent list may be used to accomplish this:

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        int numElements = 10;
        int numThreads = Environment.ProcessorCount;
        ConcurrentBag list = new ConcurrentBag();
        Random rand = new Random();
        Parallel.For(0, numThreads, i =>
        {
            for (int j = 0; j < numElements / numThreads; j++)
            {
                list.Add(rand.Next(numElements));
            }
        });
        int[] sortedList = new int[numElements];
        int index = 0;
        while (list.TryTake(out int element))
        {
            sortedList[index++] = element;
        }
        Array.Sort(sortedList);
        Console.WriteLine("Sorted list:");
        for (int i = 0; i < numElements; i++)
        {
            Console.WriteLine(sortedList[i]);
        }
    }
}

In this example, we first create a ConcurrentBag<int> object to store the list of random numbers. We use the Parallel.For method to generate the random numbers concurrently using multiple threads. The TryTake method is used to remove items from the list and add them to a regular array. Finally, we use the Array.Sort method to display the sorted list after ascendingly sorting the array.

Conclusion

In C#, a concurrent list is a thread-safe collection that allows several threads to access it concurrently without requiring external synchronization. It provides a convenient way to perform concurrent operations on a list without having to worry about thread safety issues. By including the System.Collections.Concurrent namespace and instantiating a ConcurrentBag<T> object, you can easily create and use a concurrent list in your C# programs.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.