Lire en anglais

Partager via


Hashtable.Synchronized(Hashtable) Méthode

Définition

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

C#
public static System.Collections.Hashtable Synchronized (System.Collections.Hashtable table);

Paramètres

table
Hashtable

Hashtable à synchroniser.

Retours

Wrapper synchronisé (thread-safe) pour Hashtable.

Exceptions

table a la valeur null.

Exemples

L’exemple suivant montre comment synchroniser un Hashtable, déterminer si un Hashtable est synchronisé et utiliser un synchronisé Hashtable.

C#
using System;
using System.Collections;

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

        // Creates a synchronized wrapper around the Hashtable.
        Hashtable mySyncdHT = Hashtable.Synchronized(myHT);

        // Displays the sychronization status of both Hashtables.
        Console.WriteLine("myHT is {0}.", myHT.IsSynchronized ? "synchronized" : "not synchronized");
        Console.WriteLine("mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized");
    }
}

/*
This code produces the following output.

myHT is not synchronized.
mySyncdHT is synchronized.
*/

Remarques

La Synchronized méthode est thread safe pour plusieurs lecteurs et rédacteurs. En outre, le wrapper synchronisé garantit qu’il n’y a qu’un seul rédacteur en écriture à la fois.

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.

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

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

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

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