NameObjectCollectionBase.KeysCollection.ICollection.IsSynchronized 屬性

定義

取得值,這個值表示對 NameObjectCollectionBase.KeysCollection 的存取是否同步 (安全執行緒)。

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

屬性值

如果 true 的存取為同步 (安全執行緒),則為 NameObjectCollectionBase.KeysCollection,否則為 false。 預設為 false

實作

範例

下列程式代碼範例示範如何在整個列舉期間使用 SyncRoot 鎖定 集合。

// Create a collection derived from NameObjectCollectionBase
NameObjectCollectionBase^ myBaseCollection = gcnew DerivedCollection();
// Get the ICollection from NameObjectCollectionBase.KeysCollection
ICollection^ myKeysCollection = myBaseCollection->Keys;
bool lockTaken = false;
try
{
    Monitor::Enter(myKeysCollection->SyncRoot, lockTaken);
    for each (Object^ item in myKeysCollection)
    {
        // Insert your code here.
    }
}
finally
{
    if (lockTaken)
    {
        Monitor::Exit(myKeysCollection->SyncRoot);
    }
}
// Create a collection derived from NameObjectCollectionBase
NameObjectCollectionBase myBaseCollection = new DerivedCollection();
// Get the ICollection from NameObjectCollectionBase.KeysCollection
ICollection myKeysCollection = myBaseCollection.Keys;
lock(myKeysCollection.SyncRoot)
{
    foreach (object item in myKeysCollection)
    {
        // Insert your code here.
    }
}
' Create a collection derived from NameObjectCollectionBase
Dim myBaseCollection As NameObjectCollectionBase = New DerivedCollection()
' Get the ICollection from NameObjectCollectionBase.KeysCollection
Dim myKeysCollection As ICollection = myBaseCollection.Keys
SyncLock myKeysCollection.SyncRoot
    For Each item As Object In myKeysCollection
        ' Insert your code here.
    Next item
End SyncLock

擷取這個屬性的值是一種 O(1) 運算。

備註

衍生類別可以使用 屬性提供自己的同步版本NameObjectCollectionBase.KeysCollectionSyncRoot。 同步程式代碼必須在 的 NameObjectCollectionBase.KeysCollectionSyncRoot執行作業,而不是直接在 上NameObjectCollectionBase.KeysCollection。 如此可確保衍生自其他物件的集合可以正常運作, 具體而言,它會與可能同時修改 NameObjectCollectionBase.KeysCollection 物件的其他線程維持適當的同步處理。

透過集合進行列舉在本質上並非安全執行緒程序。 即使集合經過同步化,其他的執行緒仍可修改該集合,使列舉值擲回例外狀況。 若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截由其他執行緒的變更所造成的例外狀況。

適用於

另請參閱