Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểm tra SortedList có được đồng bộ hóa trong C#

Giới thiệu

SortedList (namespace System.Collections) không đồng bộ hóa mặc định (IsSynchronized = false). Có thể tạo wrapper thread-safe bằng SortedList.Synchronized(SortedList).

Ví dụ 1: Tạo wrapper 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("Five"));
        
        SortedList sortedList = SortedList.Synchronized(list);
        Console.WriteLine("Is the SortedList synchronized? = " + sortedList.IsSynchronized);
    }
}

Kết quả

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

Ví dụ 2: SortedList gốc không 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);
    }
}

Kết quả

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

Lưu ý quan trọng về Synchronized Wrapper

  • Wrapper lock toàn bộ SortedList cho mỗi operation đơn lẻ
  • Duyệt (foreach/IDictionaryEnumerator) KHÔNG an toàn luồng
  • Phải lock thủ công trên SyncRoot khi duyệt
  • Hiệu suất kém do lock coarse-grained
// ĐÚNG - Lock khi duyệt
SortedList syncList = SortedList.Synchronized(list);
lock (syncList.SyncRoot)
{
    foreach (DictionaryEntry entry in syncList)
    {
        // An toàn
    }
}

// SAI - Không lock khi duyệt
foreach (DictionaryEntry entry in syncList) // Không an toàn!
{
    // Race condition có thể xảy ra
}

Khuyến nghị hiện đại

Thay vì SortedList (non-generic) + Synchronized, hãy dùng:

  • SortedList<TKey, TValue> (generic) + lock thủ công
  • SortedDictionary<TKey, TValue> (cây đỏ-đen, O(log n) insert/delete)
  • ConcurrentDictionary<TKey, TValue> (thread-safe, nhưng không sắp xếp)
  • ImmutableSortedDictionary<TKey, TValue> (read-only, thread-safe)

So sánh SortedList vs SortedDictionary

Đặc điểm SortedList SortedDictionary
Cấu trúc Mảng (2 mảng song song) Cây đỏ-đen (Red-Black Tree)
Memory Ít hơn Nhiều hơn
Insert/Delete O(n) - dịch chuyển mảng O(log n)
Indexed access O(1) - GetKey/GetByIndex Không hỗ trợ trực tiếp
Phù hợp Ít insert/delete, nhiều lookup by index Nhiều insert/delete, lookup by key