StringDictionary.SyncRoot Propriété

Définition

Obtient un objet qui peut être utilisé pour synchroniser l’accès à StringDictionary.

public:
 virtual property System::Object ^ SyncRoot { System::Object ^ get(); };
public virtual object SyncRoot { get; }
member this.SyncRoot : obj
Public Overridable ReadOnly Property SyncRoot As Object

Valeur de propriété

Object pouvant être utilisé pour synchroniser l’accès à StringDictionary.

Exemples

L’exemple de code suivant montre comment verrouiller la collection à l’aide du SyncRoot pendant toute l’énumération.

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

La récupération de la valeur de cette propriété est une opération O(1).

Remarques

Les classes dérivées peuvent fournir leur propre version synchronisée du à l’aide StringDictionary de la SyncRoot propriété . Le code de synchronisation doit effectuer des opérations sur le SyncRootStringDictionarydu , et non directement sur le StringDictionary. Cela garantit un bon fonctionnement des collections dérivées d’autres objets. Plus précisément, il maintient une synchronisation correcte avec d’autres threads qui peuvent modifier simultanément l’objet StringDictionary .

L'énumération d'une collection n'est intrinsèquement pas une procédure thread-safe. Même lorsqu'une collection est synchronisée, les autres threads peuvent toujours la modifier, ce qui entraîne la levée d'une exception par l'énumérateur. Pour garantir la sécurité des threads au cours de l’énumération, vous pouvez verrouiller la collection pendant l’ensemble de l’énumération ou bien intercepter les exceptions résultant des modifications apportées par les autres threads.

S’applique à