How To Get Synchronize Access To The Listdictionary In C#

Use the ListDictionary.SyncRoot Property to obtain an object that might be utilized to synchronize access to the ListDictionary. ListDictionary is a specialized collection. It is covered by the System.Collections Specialized namespace. This type represents a non-generic dictionary type. It is implemented using a linked list.

Syntax:

It has the following syntax:

Example

public virtual object SyncRoot { get; }

Property Value:

An object that allows synchronization of ListDictionary access.

  1. Shared Resource

In this particular case, a ListDictionary is the shared resource. Multiple threads can access and modify this collection at the same time.

  1. Thread Safety

Thread safety is a concept that ensures that when many threads are involved, shared resources are accessed and updated to prevent unexpected behaviour and data corruption.

  1. Locking Mechanism

locks is the main method for ensuring thread safety. The lock statement is one easy technique to synchronize access to a code block or critical section in C#.

  1. Synchronization Object

A synchronization object, often called a lock object , is a shared object that threads use to coordinate access to the critical section. It ensures that only one thread can execute the critical section at a time.

  1. Critical Section

The code that contains the access or modification of the shared resource is known as the critical section . It's the region that needs protection from concurrent access.

  1. Locking the Critical Section

A thread uses the lock statement to get a lock on the synchronization object to access the critical section. The thread can safely operate on the shared resource after it has entered the critical section.

  1. Releasing the Lock

The lock is released by the thread when it has finished working in the critical section, enabling other threads to get it and access the critical section .

  1. Concurrency Considerations

While locks ensure thread safety, they can introduce contention and affect performance. It's essential to balance synchronization and allow concurrency where possible.

  1. Alternative Synchronization Mechanisms

Other synchronization techniques such as Monitor, Mutex, Semaphore , or advanced options such as ReaderWriterLockSlim might be considered based on the specific requirements.

  1. Modern Concurrent Collections

Concurrent collections from the System are useful in contemporary C# programming. The 'Collections.Concurrent' namespace contains such as ConcurrentDictionary.

Example:

Let us take an example to illustrate how to get Synchronize access to the ListDictionary in C#.

Example

using System;
using System.Collections. Specialized;
using System.Threading;
public class SynchronizedListDictionary
{
    private ListDictionary my_Dictionary = new ListDictionary();
    private object lock_Object = new object();
    public void Add_To_Dictionary(object key, object value)
    {
        lock (lock_Object)
        {
            //Operate the lock to ensure synchronization
            my_Dictionary.Add(key, value);
            Console.WriteLine($"Added key: {key}, value: {value} to the dictionary.");
        }
    }
    public void Remove_From_Dictionary(object key)
    {
        lock (lock_Object)
        {
            //Operate the lock to ensure synchronization
            my_Dictionary.Remove(key);
            Console.WriteLine($"Removed key: {key} from the dictionary.");
        }
    }
    public object GetFromDictionary(object key)
    {
        lock (lock_Object)
        {
            //Operate the lock to ensure synchronization
            return my_Dictionary[key];
        }
    }
    // Other methods for manipulating the dictionary in a thread-safe manner
    public int DictionaryCount
    {
        get
        {
            lock (lock_Object)
            {
                //Operate the lock to ensure synchronization
                return my_Dictionary.Count;
            }
        }
    }
}

class Program
{
    static void Main()
    {
        SynchronizedListDictionary example = new SynchronizedListDictionary();
        // Creating multiple threads to manipulate the dictionary concurrently
        Thread thread_1 = new Thread(() => example.Add_To_Dictionary(1, "One"));
        Thread thread_2 = new Thread(() => example.Remove_From_Dictionary(1));
        Thread thread_3 = new Thread(() => Console.WriteLine($"Dictionary Count: {example.DictionaryCount}"));
        // Starting the threads
        thread_1.Start();
        thread_2.Start();
        thread_3.Start();
        // Waiting for threads to finish
        thread_1.Join();
        thread_2.Join();
        thread_3.Join();
        Console.ReadLine();
    }
}

Output:

Output

Added key: 1, value: One to the dictionary.
Removed key: 1 from the dictionary.
Dictionary Count: 0

Explanation:

  1. SynchronizedListDictionary Class

In this example, this class provides thread-safe dictionary manipulation methods (AddToDictionary, RemoveFromDictionary, GetFromDictionary, and DictionaryCount) and encapsulates a ListDictionary (my_Dictionary).

It uses the lock statement in each method to guarantee that only one thread may access the critical sections at a time, and it utilizes an object (lock_Object) as a synchronization object.

  1. AddToDictionary Method

Adds a key-value pair in a thread-safe manner to the dictionary. It prints a message indicating the addition and synchronizes dictionary access using the lock statement.

  1. RemoveFromDictionary Method

Removes a key in a thread-safe manner from the dictionary. It prints a message indicating the user of the removal and synchronizes dictionary access using the lock statement.

  1. GetFromDictionary Method

Retrieves a value in a thread-safe manner from the dictionary. It makes use of the lock statement to synchronize dictionary access.

  1. DictionaryCount Property

Returns a thread-safe count of the key-value pairs in the dictionary. It synchronizes dictionary access by using the lock statement.

  1. Program Class (Main Method)

Instantiates an object of SynchronizedListDictionary named example.

Creates three threads (thread1, thread2, and thread_3) that perform various dictionary operations concurrently (addition, removal, and count retrieval).

Uses 'Join' to start the threads and wait for them to finish.

Reads a line from the console to prevent the program from exiting immediately.

Input Required

This code uses input(). Please provide values below: