CollectionBase.ICollection.SyncRoot 屬性

定義

取得可用以同步存取 CollectionBase 的物件。

property System::Object ^ System::Collections::ICollection::SyncRoot { System::Object ^ get(); };
object System.Collections.ICollection.SyncRoot { get; }
member this.System.Collections.ICollection.SyncRoot : obj
 ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot

屬性值

可用來同步存取 CollectionBase 的物件。

實作

備註

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

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

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

// 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)

適用於

另請參閱