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

Các tập hợp an toàn luồng (Thread-Safe Collections) trong C#

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ớpMô tảCấu trúc dữ liệu
ConcurrentDictionary<TKey,TValue>Từ điển key-value an toàn luồngBảng băm
ConcurrentQueue<T>Hàng đợi FIFO an toàn luồngHàng đợi
ConcurrentStack<T>Ngăn xếp LIFO an toàn luồngNgăn xếp
ConcurrentBag<T>Tập hợp không thứ tự, cho phép trùng lặpTú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-consumerInterface

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.