Open In App

How to get Synchronize access to the ListDictionary in C#

ListDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the ListDictionary. ListDictionary is a specialized collection. It comes under the System.Collections.Specialized namespace. This type represents a non-generic dictionary type. It is implemented with a linked list.

Syntax: public virtual object SyncRoot { get; }



Property Value: An object which can be used to synchronize access to the ListDictionary.

Important Points:



Below programs illustrate the use of the above-discussed property:

Example 1: In this code, we are using SyncRoot to get Synchronized access to the ListDictionary named listdict, which is not a thread-safe procedure and can cause an exception. So to avoid the exception we lock the collection during the enumeration.




// C# program to illustrate the
// use of SyncRoot property of
// the ListDictionary class
using System;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
  
namespace sync_root {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // Declaring an ListDictionary
        ListDictionary listdict = new ListDictionary();
  
        // Adding elements to ListDictionary
        listdict.Add("10", "JQUERY");
        listdict.Add("20", "HTML");
        listdict.Add("30", "CSS");
        listdict.Add("40", "C");
        listdict.Add("50", "C++");
        listdict.Add("60", "C#");
  
        // Using the SyncRoot property
        lock(listdict.SyncRoot)
        {
            // foreach loop to display
            // the elements in listdict
            foreach(DictionaryEntry i in listdict)
                Console.WriteLine(i.Key + " ---- " + i.Value);
        }
    }
}
}

Output:
10 ---- JQUERY
20 ---- HTML
30 ---- CSS
40 ---- C
50 ---- C++
60 ---- C#

Example 2:




// C# program to illustrate the
// use of SyncRoot property of
// the ListDictionary class
using System;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
  
namespace sync_root {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // Declaring an ListDictionary
        ListDictionary listdict = new ListDictionary();
  
        // Adding elements to ListDictionary
        listdict.Add("1", "Ram");
        listdict.Add("2", "Shyam");
        listdict.Add("3", "Mohan");
        listdict.Add("4", "Sohan");
        listdict.Add("5", "Rohan");
  
        // Using the SyncRoot property
        lock(listdict.SyncRoot)
        {
            // foreach loop to display
            // the elements in listdict
            foreach(DictionaryEntry i in listdict)
                Console.WriteLine(i.Key + " ----> " + i.Value);
        }
    }
}
}

Output:
1 ----> Ram
2 ----> Shyam
3 ----> Mohan
4 ----> Sohan
5 ----> Rohan

Reference:


Article Tags :
C#