Open In App

How to get Synchronize access to the HybridDictionary in C#

HybridDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the HybridDictionary. It implements a linked list and hash table data structure. It implements IDictionary by using a ListDictionary when the collection is small, and a Hashtable when the collection is large.

Syntax: public virtual object SyncRoot { get; }



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

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 HybridDictionary named hd, 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 HybridDictionary 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 HybridDictionary
        HybridDictionary hd = new HybridDictionary();
  
        // Adding elements to HybridDictionary
        hd.Add("1", "HTML");
        hd.Add("2", "CSS");
        hd.Add("3", "PHP");
        hd.Add("4", "JQuery");
        hd.Add("5", "JavaScript");
  
        // Using the SyncRoot property
        lock(hd.SyncRoot)
        {
            // foreach loop to display
            // the elements in hd
            foreach(DictionaryEntry i in hd)
                Console.WriteLine(i.Key + " ---- " + i.Value);
        }
    }
}
}

Output:
1 ---- HTML
2 ---- CSS
3 ---- PHP
4 ---- JQuery
5 ---- JavaScript

Example 2:




// C# program to illustrate the
// use of SyncRoot property of
// the HybridDictionary 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 HybridDictionary
        HybridDictionary hd= new HybridDictionary();
  
        // Adding elements to HybridDictionary
        hd.Add("10", "Shyam");
        hd.Add("20", "Ram");
        hd.Add("30", "Rohit");
        hd.Add("40", "Sohan");
        hd.Add("50", "Rohan");
  
        // Using the SyncRoot property
        lock(hd.SyncRoot)
        {
            // foreach loop to display
            // the elements in hd
            foreach(DictionaryEntry i in hd)
                Console.WriteLine(i.Key + " ----> " + i.Value);
        }
    }
}
}

Output:
10 ----> Shyam
20 ----> Ram
30 ----> Rohit
40 ----> Sohan
50 ----> Rohan

Reference:


Article Tags :
C#