Hashtable.Synchronized(Hashtable) स्थैतिक मेथड निर्दिष्ट Hashtable के चारों ओर एक थ्रेड-सेफ (सिंक्रनाइज़्ड) रैपर लौटाता है। रैपर सभी ऑपरेशन्स पर लॉक करता है। मूल हैशटेबल असिंक्रनाइज़्ड रहता है।
उदाहरण 1: असिंक्रनाइज़्ड Hashtable
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
Hashtable hash = new Hashtable();
hash.Add("1", "AB");
hash.Add("2", "CD");
hash.Add("3", "EF");
hash.Add("4", "GH");
hash.Add("5", "IJ");
hash.Add("6", "KL");
Console.WriteLine("Hashtable elements...");
foreach (DictionaryEntry d in hash)
{
Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
}
Console.WriteLine("Hashtable is synchronized? = " + hash.IsSynchronized);
}
}
आउटपुट
Hashtable elements... Key = 1, Value = AB Key = 2, Value = CD Key = 3, Value = EF Key = 4, Value = GH Key = 5, Value = IJ Key = 6, Value = KL Hashtable is synchronized? = False
उदाहरण 2: सिंक्रनाइज़्ड रैपर बनाना
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
Hashtable hash = new Hashtable();
hash.Add("1", "Mark");
hash.Add("2", "Gary");
hash.Add("3", "Jacob");
hash.Add("4", "Andy");
hash.Add("5", "Jack");
Console.WriteLine("Hashtable elements...");
foreach (DictionaryEntry d in hash)
{
Console.WriteLine("Key = " + d.Key + ", Value = " + d.Value);
}
Console.WriteLine("Hashtable is synchronized? = " + hash.IsSynchronized);
Hashtable hash2 = Hashtable.Synchronized(hash);
Console.WriteLine("Hashtable is synchronized? = " + hash2.IsSynchronized);
}
}
आउटपुट
Hashtable elements... Key = 1, Value = Mark Key = 2, Value = Gary Key = 3, Value = Jacob Key = 4, Value = Andy Key = 5, Value = Jack Hashtable is synchronized? = False Hashtable is synchronized? = True
Synchronized रैपर प्रत्येक सार्वजनिक मेथड पर लॉक करता है, बुनियादी थ्रेड सुरक्षा प्रदान करता है। हालांकि, कंपाउंड ऑपरेशन्स (जैसे Check-Then-Act) के लिए बाहरी लॉकिंग की अभी भी आवश्यकता होती है। आधुनिक कोड में ConcurrentDictionary<TKey, TValue> पसंद किया जाता है।