Hashtable ডিফল্টভাবে থ্রেড-সেফ নয়। Hashtable.Synchronized() স্ট্যাটিক মেথড ব্যবহার করে একটি থ্রেড-সেফ র্যাপার পাওয়া যায়। IsSynchronized প্রপার্টি চেক করে সিঙ্ক্রোনাইজেশন স্ট্যাটাস জানা যায়।
উদাহরণ ১: সিঙ্ক্রোনাইজড হ্যাশটেবল তৈরি
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add("One", "Katie");
hash.Add("Two", "John");
hash.Add("Three", "Barry");
hash.Add("Four", "");
hash.Add("Five", "Harry");
hash.Add("Six", "F");
hash.Add("Seven", "Tom");
hash.Add("Eight", "Andy");
hash.Add("Nine", "I");
hash.Add("Ten", "Tim");
Console.WriteLine("Hashtable কী এবং মান জোড়া...");
foreach(DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Hashtable-র নির্দিষ্ট আকার? = " + hash.IsFixedSize);
Console.WriteLine("Hashtable রিড-অনলি? = " + hash.IsReadOnly);
Hashtable hash2 = Hashtable.Synchronized(hash);
Console.WriteLine("Hash সিঙ্ক্রোনাইজড? = " + hash2.IsSynchronized);
}
}
আউটপুট
Hashtable কী এবং মান জোড়া...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and
Eight and Andy
Nine and I
Six and F
Hashtable-র নির্দিষ্ট আকার? = False
Hashtable রিড-অনলি? = False
Hash সিঙ্ক্রোনাইজড? = True
উদাহরণ ২: ডিফল্ট হ্যাশটেবল (নন-সিঙ্ক্রোনাইজড)
using System;
using System.Collections;
public class Demo {
public static void Main() {
Hashtable hash = new Hashtable();
hash.Add("One", 1);
hash.Add("Two", 2);
hash.Add("Three", 2);
hash.Add("Four", 4);
hash.Add("Five", 5);
hash.Add("Six", 6);
hash.Add("Seven", 7);
Console.WriteLine("Hashtable কী এবং মান জোড়া...");
foreach(DictionaryEntry entry in hash) {
Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
}
Console.WriteLine("Hashtable-র নির্দিষ্ট আকার? = " + hash.IsFixedSize);
Console.WriteLine("Hashtable রিড-অনলি? = " + hash.IsReadOnly);
Console.WriteLine("Hash সিঙ্ক্রোনাইজড? = " + hash.IsSynchronized);
}
}
আউটপুট
Hashtable কী এবং মান জোড়া...
One and 1
Five and 5
Three and 2
Seven and 7
Two and 2
Four and 4
Six and 6
Hashtable-র নির্দিষ্ট আকার? = False
Hashtable রিড-অনলি? = False
Hash সিঙ্ক্রোনাইজড? = False
সতর্কতা: Synchronized র্যাপার সব মেথডে লক দিয়ে থ্রেড সেফটি নিশ্চিত করে, তবে এনিউমারেশন করার সময় ম্যানুয়াল লক দরকার। আধুনিক কোডে ConcurrentDictionary ব্যবহার করুন।