Từ .NET Framework 4, namespace System.Collections.Concurrent cung cấp các tập hợp an toàn luồng (thread-safe) và có khả năng mở rộng (scalable). Nhiều luồng có thể thêm/xóa phần tử an toàn mà không cần khóa thủ công.
Các loại tập hợp concurrent chính
| Tên lớp | Mô tả | Cấu trúc dữ liệu |
|---|---|---|
ConcurrentDictionary<TKey,TValue> | Từ điển key-value an toàn luồng | Bảng băm |
ConcurrentQueue<T> | Hàng đợi FIFO an toàn luồng | Hàng đợi |
ConcurrentStack<T> | Ngăn xếp LIFO an toàn luồng | Ngăn xếp |
ConcurrentBag<T> | Tập hợp không thứ tự, cho phép trùng lặp | Túi |
BlockingCollection<T> | Bao bọc tập hợp khác, hỗ trợ chặn/đợi (bounding/blocking) | Wrapper |
IProducerConsumerCollection<T> | Interface cho tập hợp producer-consumer | Interface |
Ví dụ: ConcurrentDictionary
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
class Program
{
static ConcurrentDictionary cache = new ConcurrentDictionary();
static void Main()
{
// Thêm/cập nhật an toàn
cache.AddOrUpdate("key1", 1, (k, v) => v + 1);
cache.TryAdd("key2", 100);
// Đọc an toàn
if (cache.TryGetValue("key1", out int val))
Console.WriteLine($"key1 = {val}");
// Song song nhiều luồng
Parallel.For(0, 1000, i =>
{
cache.AddOrUpdate("counter", 1, (k, v) => v + 1);
});
Console.WriteLine($"Counter: {cache["counter"]}"); // 1000
}
}
Cơ chế: Dùng SpinLock, SpinWait, CAS (Compare-And-Swap) - khóa nhẹ, không block luồng OS.