Hashtable.Synchronized(Hashtable) Método

Definição

Retorna um wrapper sincronizado (thread-safe) para o Hashtable.

public:
 static System::Collections::Hashtable ^ Synchronized(System::Collections::Hashtable ^ table);
public static System.Collections.Hashtable Synchronized (System.Collections.Hashtable table);
static member Synchronized : System.Collections.Hashtable -> System.Collections.Hashtable
Public Shared Function Synchronized (table As Hashtable) As Hashtable

Parâmetros

table
Hashtable

O Hashtable a ser sincronizado.

Retornos

Um wrapper sincronizado (thread-safe) para o Hashtable.

Exceções

table é null.

Exemplos

O exemplo a seguir mostra como sincronizar um Hashtable, determinar se um Hashtable é sincronizado e usar um sincronizado Hashtable.

#using <system.dll>

using namespace System;
using namespace System::Collections;
void main()
{
   
   // Creates and initializes a new Hashtable.
   Hashtable^ myHT = gcnew Hashtable;
   myHT->Add( (int^)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 ? (String^)"synchronized" : "not synchronized" );
   Console::WriteLine( "mySyncdHT is {0}.", mySyncdHT->IsSynchronized ? (String^)"synchronized" : "not synchronized" );
}

/*
 This code produces the following output.

 myHT is not synchronized.
 mySyncdHT is synchronized.
 */
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.
*/
Imports System.Collections

Public Class SamplesHashtable    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Hashtable.
        Dim myHT As 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.
        Dim mySyncdHT As Hashtable = Hashtable.Synchronized(myHT)
        
        ' Displays the sychronization status of both Hashtables.
        Dim msg As String = If(myHT.IsSynchronized, "synchronized", "not synchronized")
        Console.WriteLine($"myHT is {msg}.")
        msg = If(mySyncdHT.IsSynchronized, "synchronized", "not synchronized")
        Console.WriteLine($"mySyncdHT is {msg}.")
    End Sub
End Class

' This code produces the following output.
' 
' myHT is not synchronized.
' mySyncdHT is synchronized.

Comentários

O Synchronized método é thread-safe para vários leitores e gravadores. Além disso, o wrapper sincronizado garante que haja apenas um gravador escrevendo por vez.

A enumeração por meio de uma coleção não é um procedimento thread-safe intrínseco. Mesmo quando uma coleção está sincronizada, outros threads ainda podem modificar a coleção, o que faz o enumerador lançar uma exceção. Para garantir thread-safe durante a enumeração, é possível bloquear a coleção durante toda a enumeração ou verificar as exceções resultantes das alterações feitas por outros threads.

O exemplo de código a seguir mostra como bloquear a coleção usando o SyncRoot durante toda a enumeração:

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

Esse método é uma O(1) operação.

Aplica-se a

Confira também