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

Interface ICollection ใน C#

Interface ICollection ใน C#

ICollection (Non-generic) เป็น Base Interface สำหรับ Non-generic Collections ทั้งหมดใน System.Collections กำหนด Size, Enumerators, Synchronization

Properties

Propertyคำอธิบาย
Countจำนวน Element ใน Collection
IsSynchronizedThread-safe หรือไม่
SyncRootObject สำหรับ 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 - แนะนำ)

MemberICollection (Non-generic)ICollection<T> (Generic)
Countint Count { get; }int Count { get; }
SyncRootobject SyncRoot { get; }ไม่มี (ใช้ Lock แยก)
IsSynchronizedbool IsSynchronized { get; }ไม่มี
CopyToCopyTo(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>