CollectionBase.ICollection.IsSynchronized 屬性

定義

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

property bool System::Collections::ICollection::IsSynchronized { bool get(); };
bool System.Collections.ICollection.IsSynchronized { get; }
member this.System.Collections.ICollection.IsSynchronized : bool
 ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized

屬性值

Boolean

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

實作

備註

CollectionBase實例未同步處理。A CollectionBase instance is not synchronized. 衍生類別可以使用屬性提供同步處理的版本 CollectionBase SyncRootDerived classes can provide a synchronized version of the CollectionBase using the SyncRoot property.

列舉集合本質上並不是執行緒安全的程式。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 during the entire enumeration:

// Get the ICollection interface from the CollectionBase
// derived class.
ICollection^ myCollection = myCollectionBase;
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);
    }
}
// Get the ICollection interface from the CollectionBase
// derived class.
ICollection myCollection = myCollectionBase;
lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
' Get the ICollection interface from the CollectionBase
' derived class.
Dim myCollection As ICollection = myCollectionBase
SyncLock myCollection.SyncRoot
    For Each item As Object In myCollection
        ' Insert your code here.
    Next item
End SyncLock

抓取這個屬性的值是一項作業 O(1)Retrieving the value of this property is an O(1) operation.

適用於

另請參閱