NameObjectCollectionBase.ICollection.SyncRoot Proprietà

Definizione

Ottiene un oggetto che può essere usato per sincronizzare l'accesso all'oggetto NameObjectCollectionBase.

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

Valore della proprietà

Oggetto che può essere usato per sincronizzare l'accesso all'oggetto NameObjectCollectionBase.

Implementazioni

Commenti

Le classi derivate possono fornire la propria versione sincronizzata della NameObjectCollectionBase classe usando la SyncRoot proprietà . Il codice di sincronizzazione deve eseguire operazioni sulla SyncRoot proprietà dell'oggetto NameObjectCollectionBase , non direttamente sull'oggetto NameObjectCollectionBase . In questo modo si garantisce il corretto funzionamento delle raccolte derivate da altri oggetti. In particolare, mantiene una corretta sincronizzazione con altri thread che potrebbero modificare contemporaneamente l'oggetto NameObjectCollectionBase .

L'enumerazione di una raccolta non è di per sé una procedura thread-safe. Anche se una raccolta è sincronizzata, è possibile che venga modificata da altri thread, con conseguente generazione di un'eccezione da parte dell'enumeratore. Per garantire la protezione dei thread durante l'enumerazione, è possibile bloccare la raccolta per l'intera enumerazione oppure intercettare le eccezioni determinate dalle modifiche apportate da altri thread.

Nell'esempio di codice seguente viene illustrato come bloccare la raccolta usando durante SyncRoot l'intera enumerazione .

// Create a collection derived from NameObjectCollectionBase
ICollection^ myCollection = gcnew DerivedCollection();
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);
    }
}
// Create a collection derived from NameObjectCollectionBase
ICollection myCollection = new DerivedCollection();
lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
' Create a collection derived from NameObjectCollectionBase
Dim myCollection As ICollection = New DerivedCollection()
SyncLock myCollection.SyncRoot
    For Each item As Object In myCollection
        ' Insert your code here.
    Next item
End SyncLock

Il recupero del valore di questa proprietà è un'operazione O(1).

Si applica a

Vedi anche