ภาพรวม
เมธอด static SortedList.Synchronized(SortedList) สร้าง synchronized wrapper สำหรับ SortedList คุณสมบัติ IsSynchronized บอกว่าเป็น wrapper หรือไม่
ตัวอย่างที่ 1: สร้าง Synchronized Wrapper
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
SortedList list = new SortedList();
list.Add("1", "One");
list.Add("2", "Two");
list.Add("3", "Three");
list.Add("4", "Four");
list.Add("5", "Five");
list.Add("6", "Six");
list.Add("7", "Seven");
list.Add("8", "Eight");
Console.WriteLine("Key and Value of SortedList....");
foreach(DictionaryEntry k in list)
Console.WriteLine("Key: {0}, Value: {1}", k.Key, k.Value);
Console.WriteLine("Is the SortedList having the value? " + list.ContainsValue("Five"));
SortedList sortedList = SortedList.Synchronized(list);
Console.WriteLine("Is the SortedList synchronized? = " + sortedList.IsSynchronized);
}
}
ผลลัพธ์
Key and Value of SortedList....
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value = Four
Key: 5, Value: Five
Key: 6, Value: Six
Key: 7, Value: Seven
Key: 8, Value: Eight
Is the SortedList having the value? True
Is the SortedList synchronized? = True
ตัวอย่างที่ 2: SortedList ธรรมดา (ไม่ synchronized)
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
SortedList list = new SortedList();
list.Add("1", "One");
list.Add("2", "Two");
list.Add("3", "Three");
list.Add("4", "Four");
list.Add("5", "Five");
list.Add("6", "Six");
list.Add("7", "Seven");
list.Add("8", "Eight");
Console.WriteLine("Key and Value of SortedList....");
foreach(DictionaryEntry k in list)
Console.WriteLine("Key: {0}, Value: {1}", k.Key, k.Value);
Console.WriteLine("Is the SortedList having the value? " + list.ContainsValue("Ten"));
Console.WriteLine("Is the SortedList synchronized? = " + list.IsSynchronized);
}
}
ผลลัพธ์
Key and Value of SortedList....
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
Key: 4, Value: Four
Key: 5, Value: Five
Key: 6, Value: Six
Key: 7, Value: Seven
Key: 8, Value: Eight
Is the SortedList having the value? False
Is the SortedList synchronized? = False
คำอธิบายเพิ่มเติม
SortedList.Synchronized(list)คืนค่า wrapper ที่ล็อกทุก operation สาธารณะ- การวนลูป (foreach) **ไม่ได้** thread-safe แม้จะเป็น synchronized wrapper ต้องล็อกด้วย SyncRoot
- SortedList ธรรมดา: IsSynchronized = false, IsFixedSize = false, IsReadOnly = false
- SortedList ใช้ binary search O(log n) สำหรับค้นหา เรียงตามคีย์อัตโนมัติ
- สำหรับโค้ดใหม่ แนะนำ
SortedList<TKey, TValue>(generic) + lock หรือConcurrentDictionary<TKey, TValue>(ไม่เรียง) หรือ third-party concurrent sorted dictionary