ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized Property

定義

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

public:
 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;
try
{
    Monitor::Enter(myCollection->SyncRoot, lockTaken);
    for each (Object^ item in myCollection);
    {
        // Insert your code here.
    }
}
finally
{
    if (lockTaken)
    {
        Monitor::Exit(myCollection->SyncRoot);
    }
}
ICollection myCollection = someCollection;
lock(myCollection.SyncRoot)
{
    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

適用於

另請參閱