Lire en anglais

Partager via


SortedList.Synchronized(SortedList) Méthode

Définition

Retourne un wrapper synchronisé (thread-safe) pour un objet SortedList.

C#
public static System.Collections.SortedList Synchronized (System.Collections.SortedList list);

Paramètres

list
SortedList

Objet SortedList à synchroniser.

Retours

Wrapper synchronisé (thread-safe) pour l'objet SortedList.

Exceptions

list a la valeur null.

Exemples

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

C#
SortedList myCollection = new SortedList();
lock (myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}

Cette méthode est une O(1) opération.

L’exemple de code suivant montre comment synchroniser un SortedList objet, déterminer si un SortedList est synchronisé et utiliser un synchronisé SortedList.

C#
using System;
using System.Collections;

public class SamplesSortedList
{
    public static void Main()
    {
        // Creates and initializes a new SortedList.
        SortedList mySL = new SortedList();
        mySL.Add(2, "two");
        mySL.Add(3, "three");
        mySL.Add(1, "one");
        mySL.Add(0, "zero");
        mySL.Add(4, "four");

        // Creates a synchronized wrapper around the SortedList.
        SortedList mySyncdSL = SortedList.Synchronized(mySL);

        // Displays the sychronization status of both SortedLists.
        Console.WriteLine("mySL is {0}.", mySL.IsSynchronized ? "synchronized" : "not synchronized");
        Console.WriteLine("mySyncdSL is {0}.", mySyncdSL.IsSynchronized ? "synchronized" : "not synchronized");
    }
}
/*
This code produces the following output.

mySL is not synchronized.
mySyncdSL is synchronized.
*/

Remarques

Pour garantir la sécurité du thread d’un SortedList objet, toutes les opérations doivent être effectuées uniquement via ce wrapper.

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 à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Voir aussi