ภาพรวม
เมธอด static Hashtable.Synchronized(Hashtable) คืนค่า wrapper ที่เป็น thread-safe (synchronized) สำหรับ Hashtable ที่ส่งเข้า ใช้สำหรับการเข้าถึงจากหลายเธรด
ตัวอย่างที่ 1: Hashtable ธรรมดา (ไม่ synchronized)
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: สร้าง Synchronized Wrapper
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
คำอธิบายเพิ่มเติม
- Wrapper ที่คืนจาก
Synchronized()ล็อก (lock) ทุกการดำเนินการ (Add, Remove, indexer, Count, ฯลฯ) - การวนลูป (enumeration) ไม่ได้** thread-safe** แม้จะเป็น synchronized wrapper ต้องล็อกเองระหว่าง foreach
- Hashtable เป็น legacy ใช้
ConcurrentDictionary<TKey, TValue>(namespace System.Collections.Concurrent) สำหรับ thread-safe แบบสมัยใหม่ IsSynchronizedproperty ตรวจสอบว่าเป็น synchronized wrapper หรือไม่