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ớp | Mô tả | Use case |
|---|---|---|
ConcurrentDictionary<TKey,TValue> | Dictionary thread-safe | Cache, shared state |
ConcurrentQueue<T> | FIFO queue thread-safe | Task queue, message bus |
ConcurrentStack<T> | LIFO stack thread-safe | Object pool, undo stack |
ConcurrentBag<T> | Unordered bag thread-safe | Thread-local storage merge |
BlockingCollection<T> | Wrapper có blocking/bounding | Producer-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.