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