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

Tập hợp Concurrent an toàn luồng trong C#

Namespace System.Collections.Concurrent (.NET 4+) cung cấp tập hợp thread-safe, scalable cho producer-consumer patterns.

Các loại chính

LớpMô tảUse case
ConcurrentDictionary<TKey,TValue>Dictionary thread-safeCache, shared state
ConcurrentQueue<T>FIFO queue thread-safeTask queue, message bus
ConcurrentStack<T>LIFO stack thread-safeObject pool, undo stack
ConcurrentBag<T>Unordered bag thread-safeThread-local storage merge
BlockingCollection<T>Wrapper có blocking/boundingProducer-consumer pipeline

Ví dụ: ConcurrentStack

using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program
{
    static ConcurrentStack stack = new ConcurrentStack();
    
    static void Main()
    {
        // Producer
        Parallel.For(0, 1000, i => stack.Push(i));
        Console.WriteLine($"Pushed 1000, Count: {stack.Count}");
        
        // Consumer
        int popped = 0;
        while (stack.TryPop(out int _)) popped++;
        Console.WriteLine($"Popped: {popped}");
        
        // TryPeek - xem top không xóa
        stack.Push(42);
        if (stack.TryPeek(out int top))
            Console.WriteLine($"Top: {top}"); // 42
    }
}

Ví dụ: BlockingCollection (Producer-Consumer)

var queue = new BlockingCollection(boundedCapacity: 100);

// Producer
Task.Run(() => {
    for (int i = 0; i < 10; i++)
    {
        queue.Add(i); // Block nếu full
        Console.WriteLine($"Produced {i}");
    }
    queue.CompleteAdding();
});

// Consumer
Task.Run(() => {
    foreach (int item in queue.GetConsumingEnumerable())
    {
        Console.WriteLine($"Consumed {item}");
    }
}).Wait();

Ưu điểm: Lock-free (CAS), scalable, không deadlock, API đơn giản.