Giới thiệu
ArrayList.Synchronized(ArrayList) trả về wrapper an toàn luồng cho ArrayList. ArrayList gốc không đồng bộ hóa (IsSynchronized = false).
Ví dụ 1: ArrayList gốc không đồng bộ
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add("AB");
arrList.Add("CD");
arrList.Add("EF");
arrList.Add("GH");
arrList.Add("IJ");
arrList.Add("KL");
Console.WriteLine("ArrayList elements...");
foreach (string str in arrList)
{
Console.WriteLine(str);
}
Console.WriteLine("ArrayList is synchronized? = " + arrList.IsSynchronized);
}
}
Kết quả
ArrayList elements... AB CD EF GH IJ KL ArrayList is synchronized? = False
Ví dụ 2: Tạo wrapper Synchronized
using System;
using System.Collections;
public class Demo
{
public static void Main()
{
ArrayList arrList = new ArrayList();
arrList.Add("AB");
arrList.Add("CD");
arrList.Add("EF");
arrList.Add("GH");
arrList.Add("IJ");
arrList.Add("KL");
Console.WriteLine("ArrayList elements...");
foreach (string str in arrList)
{
Console.WriteLine(str);
}
Console.WriteLine("ArrayList is synchronized? = " + arrList.IsSynchronized);
ArrayList arrList2 = ArrayList.Synchronized(arrList);
Console.WriteLine("ArrayList is synchronized? = " + arrList2.IsSynchronized);
}
}
Kết quả
ArrayList elements... AB CD EF GH IJ KL ArrayList is synchronized? = False ArrayList is synchronized? = True
Lưu ý quan trọng về Synchronized Wrapper
- Wrapper lock toàn bộ ArrayList cho mỗi operation đơn lẻ
- Duyệt (foreach) KHÔNG an toàn luồng ngay cả với wrapper
- Phải lock thủ công trên
SyncRootkhi duyệt - Hiệu suất kém do contention trên lock toàn bộ
// ĐÚNG - Lock khi duyệt
ArrayList syncList = ArrayList.Synchronized(list);
lock (syncList.SyncRoot)
{
foreach (var item in syncList)
{
// An toàn
}
}
// SAI - Không lock khi duyệt
foreach (var item in syncList) // Race condition!
{
// Không an toàn
}
Khuyến nghị hiện đại
Thay vì ArrayList + Synchronized, hãy dùng:
List<T>+lockthủ công (đơn giản)ConcurrentBag<T>,ConcurrentQueue<T>,ConcurrentStack<T>(lock-free)ImmutableList<T>cho read-only thread-safeSystem.Collections.Concurrentnamespace
So sánh hiệu suất
| Cách tiếp cận | Độ phức tạp | Hiệu suất đa luồng |
|---|---|---|
| ArrayList.Synchronized | Lock toàn bộ | Thấp (contention cao) |
| List<T> + lock | Lock tùy chỉnh | Trung bình |
| Concurrent collections | Lock-free / fine-grained | Cao |
| Immutable collections | Read-only, no lock | Cao nhất cho read-heavy |