Interface ICollection ใน C#
ICollection (Non-generic) เป็น Base Interface สำหรับ Non-generic Collections ทั้งหมดใน System.Collections กำหนด Size, Enumerators, Synchronization
Properties
| Property | คำอธิบาย |
Count | จำนวน Element ใน Collection |
IsSynchronized | Thread-safe หรือไม่ |
SyncRoot | Object สำหรับ Lock (Thread Synchronization) |
Methods
| Method | คำอธิบาย |
CopyTo(Array, int index) | Copy Elements ไป Array เริ่มที่ Index |
GetEnumerator() | คืน IEnumerator สำหรับ Iteration |
Hierarchy
IEnumerable
↑
ICollection (Count, SyncRoot, CopyTo)
↑
IList (Indexer, Add, Remove, Insert, etc.)
↑
ArrayList, Array, etc.
ตัวอย่าง: ใช้ SyncRoot สำหรับ Thread Safety
using System;
using System.Collections;
using System.Threading;
class Program
{
static ArrayList sharedList = new ArrayList();
static readonly object syncLock = new object(); // Better than SyncRoot for custom logic
static void AddItems(int count)
{
for (int i = 0; i < count; i++)
{
lock (syncLock) // หรือ lock(sharedList.SyncRoot)
{
sharedList.Add(i);
}
}
}
static void Main()
{
Thread t1 = new Thread(() => AddItems(1000));
Thread t2 = new Thread(() => AddItems(1000));
t1.Start(); t2.Start();
t1.Join(); t2.Join();
Console.WriteLine($"Expected: 2000, Actual: {sharedList.Count}");
}
}
ICollection<T> (Generic - แนะนำ)
| Member | ICollection (Non-generic) | ICollection<T> (Generic) |
| Count | int Count { get; } | int Count { get; } |
| SyncRoot | object SyncRoot { get; } | ไม่มี (ใช้ Lock แยก) |
| IsSynchronized | bool IsSynchronized { get; } | ไม่มี |
| CopyTo | CopyTo(Array, int) | CopyTo(T[], int) |
| Add/Remove/Clear | ไม่มี (อยู่ใน IList) | Add(T), Remove(T), Clear() |
| Contains | ไม่มี | Contains(T) |
| IsReadOnly | ไม่มี | bool IsReadOnly { get; } |
Best Practice
- ใช้
ICollection<T> หรือ IList<T> แทน Non-generic Versions
- หลีกเลี่ยง
SyncRoot / IsSynchronized - ใช้ lock บน Private Object แทน
- Thread-safe Collections:
ConcurrentBag<T>, ConcurrentDictionary<TKey,TValue>, BlockingCollection<T>