ICollection.IsSynchronized 屬性


取得值,這個值表示對 ICollection 的存取是否同步 (安全執行緒)。Gets a value indicating whether access to the ICollection is synchronized (thread safe).

 property bool IsSynchronized { bool get(); };
public bool IsSynchronized { get; }
member this.IsSynchronized : bool
Public ReadOnly Property IsSynchronized As Boolean



如果 true 的存取為同步 (安全執行緒),則為 ICollection,否則為 falsetrue if access to the ICollection is synchronized (thread safe); otherwise, false.


SyncRoot 會傳回物件,該物件可用來同步處理對 ICollection 的存取。SyncRoot returns an object, which can be used to synchronize access to the ICollection.

命名空間中大部分的集合類別 System.Collections 也會執行同步處理的方法,它會在基礎集合周圍提供同步的包裝函式。Most collection classes in the System.Collections namespace also implement a Synchronized method, which provides a synchronized wrapper around the underlying collection.

透過集合進行列舉在本質上並非安全執行緒程序。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使集合經過同步化,其他的執行緒仍可修改該集合,使列舉值擲回例外狀況。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截由其他執行緒的變更所造成的例外狀況。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

下列程式碼範例示範如何使用 SyncRoot 屬性在整個列舉期間鎖定集合。The following code example shows how to lock the collection using the SyncRoot property during the entire enumeration.

ICollection^ myCollection = someCollection;
bool lockTaken = false;
    Monitor::Enter(myCollection->SyncRoot, lockTaken);
    for each (Object^ item in myCollection);
        // Insert your code here.
    if (lockTaken)
ICollection myCollection = someCollection;
    foreach (object item in myCollection)
        // Insert your code here.
Dim myCollection As ICollection = someCollection
SyncLock myCollection.SyncRoot
    For Each item In myCollection
        ' Insert your code here.
    Next item
End SyncLock