Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ทำให้ Collections เป็น Thread-Safe ใน C# ด้วย Concurrent Collections


.NET Framework 4 นำเข้า Namespace System.Collections.Concurrent ซึ่งมี Collection Classes หลายตัวที่เป็น Thread-Safe และ Scalable Collections เหล่านี้เรียกว่า Concurrent Collections เพราะเข้าถึงได้หลาย Thread พร้อมกัน

Concurrent Collection Types ต่อไปนี้ใช้ Lightweight Synchronization Mechanisms: SpinLock, SpinWait, ฯลฯ ซึ่งใหม่ใน .NET Framework 4

รายการ Concurrent Collections ใน C#:

Type Description
BlockingCollection<T> Bounding และ Blocking Functionality สำหรับ Type ใดๆ
ConcurrentDictionary<TKey,TValue> Thread-safe Implementation ของ Dictionary ของ Key-Value Pairs
ConcurrentQueue<T> Thread-safe Implementation ของ FIFO (First-In, First-Out) Queue
ConcurrentStack<T> Thread-safe Implementation ของ LIFO (Last-In, First-Out) Stack
ConcurrentBag<T> Thread-safe Implementation ของ Unordered Collection ของ Elements
IProducerConsumerCollection<T> Interface ที่ Type ต้อง Implement เพื่อใช้ใน BlockingCollection

ตัวอย่างการใช้งาน ConcurrentStack<T> ซึ่งเป็น Thread-Safe LIFO Collection:

ConcurrentStack<int> cs = new ConcurrentStack<int>(); 
cs.Push(95); 
cs.Push(120); 
cs.Push(130);