Thread.GetData(LocalDataStoreSlot) Méthode

Définition

Récupère la valeur de l'emplacement spécifié sur le thread actif, dans le domaine actuel du thread actif. Pour de meilleures performances, utilisez à la place les champs marqués avec l'attribut ThreadStaticAttribute.

public:
 static System::Object ^ GetData(LocalDataStoreSlot ^ slot);
public static object? GetData (LocalDataStoreSlot slot);
public static object GetData (LocalDataStoreSlot slot);
static member GetData : LocalDataStoreSlot -> obj
Public Shared Function GetData (slot As LocalDataStoreSlot) As Object

Paramètres

slot
LocalDataStoreSlot

LocalDataStoreSlot à partir duquel obtenir la valeur.

Retours

Object

Valeur récupérée.

Exemples

Cette section contient deux exemples de code. Le premier exemple montre comment utiliser un champ qui est marqué avec l' ThreadStaticAttribute attribut pour contenir des informations spécifiques au thread. Le deuxième exemple montre comment utiliser un emplacement de données pour effectuer la même opération.

Premier exemple

L’exemple suivant montre comment utiliser un champ marqué avec ThreadStaticAttribute pour conserver les informations spécifiques aux threads. Cette technique offre de meilleures performances que la technique présentée dans le deuxième exemple.

using namespace System;
using namespace System::Threading;

ref class ThreadData
{
private:
   [ThreadStatic]
   static int threadSpecificData;

public:
   static void ThreadStaticDemo()
   {
      // Store the managed thread id for each thread in the static
      // variable.
      threadSpecificData = Thread::CurrentThread->ManagedThreadId;
      
      // Allow other threads time to execute the same code, to show
      // that the static data is unique to each thread.
      Thread::Sleep( 1000 );

      // Display the static data.
      Console::WriteLine( "Data for managed thread {0}: {1}", 
         Thread::CurrentThread->ManagedThreadId, threadSpecificData );
   }
};

int main()
{
   for ( int i = 0; i < 3; i++ )
   {
      Thread^ newThread = 
          gcnew Thread( gcnew ThreadStart( ThreadData::ThreadStaticDemo )); 
      newThread->Start();
   }
}

/* This code example produces output similar to the following:

Data for managed thread 4: 4
Data for managed thread 5: 5
Data for managed thread 3: 3
 */
using System;
using System.Threading;

class Test
{
    static void Main()
    {
        for(int i = 0; i < 3; i++)
        {
            Thread newThread = new Thread(ThreadData.ThreadStaticDemo);
            newThread.Start();
        }
    }
}

class ThreadData
{
    [ThreadStatic]
    static int threadSpecificData;

    public static void ThreadStaticDemo()
    {
        // Store the managed thread id for each thread in the static
        // variable.
        threadSpecificData = Thread.CurrentThread.ManagedThreadId;
      
        // Allow other threads time to execute the same code, to show
        // that the static data is unique to each thread.
        Thread.Sleep( 1000 );

        // Display the static data.
        Console.WriteLine( "Data for managed thread {0}: {1}", 
            Thread.CurrentThread.ManagedThreadId, threadSpecificData );
    }
}

/* This code example produces output similar to the following:

Data for managed thread 4: 4
Data for managed thread 5: 5
Data for managed thread 3: 3
 */
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()

        For i As Integer = 1 To 3
            Dim newThread As New Thread(AddressOf ThreadData.ThreadStaticDemo)
            newThread.Start()
        Next i

    End Sub

End Class

Class ThreadData

    <ThreadStatic> _
    Shared threadSpecificData As Integer

    Shared Sub ThreadStaticDemo()

        ' Store the managed thread id for each thread in the static
        ' variable.
        threadSpecificData = Thread.CurrentThread.ManagedThreadId
      
        ' Allow other threads time to execute the same code, to show
        ' that the static data is unique to each thread.
        Thread.Sleep( 1000 )

        ' Display the static data.
        Console.WriteLine( "Data for managed thread {0}: {1}", _
            Thread.CurrentThread.ManagedThreadId, threadSpecificData )

    End Sub

End Class

' This code example produces output similar to the following:
'
'Data for managed thread 4: 4
'Data for managed thread 5: 5
'Data for managed thread 3: 3

Deuxième exemple

L’exemple suivant montre comment utiliser un emplacement de données pour stocker des informations spécifiques aux threads.

using namespace System;
using namespace System::Threading;
ref class Slot
{
private:
   static Random^ randomGenerator;
   static LocalDataStoreSlot^ localSlot;
   static Slot()
   {
      randomGenerator = gcnew Random;
      localSlot = Thread::AllocateDataSlot();
   }


public:
   static void SlotTest()
   {
      
      // Set different data in each thread's data slot.
      Thread::SetData( localSlot, randomGenerator->Next( 1, 200 ) );
      
      // Write the data from each thread's data slot.
      Console::WriteLine( "Data in thread_{0}'s data slot: {1,3}", AppDomain::GetCurrentThreadId().ToString(), Thread::GetData( localSlot )->ToString() );
      
      // Allow other threads time to execute SetData to show
      // that a thread's data slot is unique to the thread.
      Thread::Sleep( 1000 );
      Console::WriteLine( "Data in thread_{0}'s data slot: {1,3}", AppDomain::GetCurrentThreadId().ToString(), Thread::GetData( localSlot )->ToString() );
   }

};

int main()
{
   array<Thread^>^newThreads = gcnew array<Thread^>(4);
   for ( int i = 0; i < newThreads->Length; i++ )
   {
      newThreads[ i ] = gcnew Thread( gcnew ThreadStart( &Slot::SlotTest ) );
      newThreads[ i ]->Start();

   }
}
using System;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread[] newThreads = new Thread[4];
        for(int i = 0; i < newThreads.Length; i++)
        {
            newThreads[i] = new Thread(
                new ThreadStart(Slot.SlotTest));
            newThreads[i].Start();
        }
    }
}

class Slot
{
    static Random randomGenerator;
    static LocalDataStoreSlot localSlot;

    static Slot()
    {
        randomGenerator = new Random();
        localSlot = Thread.AllocateDataSlot();
    }

    public static void SlotTest()
    {
        // Set different data in each thread's data slot.
        Thread.SetData(localSlot, randomGenerator.Next(1, 200));

        // Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(localSlot).ToString());

        // Allow other threads time to execute SetData to show
        // that a thread's data slot is unique to the thread.
        Thread.Sleep(1000);

        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(localSlot).ToString());
    }
}
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim newThreads(3) As Thread
        For i As Integer = 0 To newThreads.Length - 1
            newThreads(i) = New Thread(AddressOf Slot.SlotTest)
            newThreads(i).Start()
        Next i
    End Sub

End Class

Public Class Slot

    Shared randomGenerator As Random
    Shared localSlot As LocalDataStoreSlot

    Shared Sub New()
        randomGenerator = new Random()
        localSlot = Thread.AllocateDataSlot()
    End Sub

    Shared Sub SlotTest()

        ' Set different data in each thread's data slot.
        Thread.SetData(localSlot, randomGenerator.Next(1, 200))

        ' Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData(localSlot).ToString())

        ' Allow other threads time to execute SetData to show
        ' that a thread's data slot is unique to the thread.
        Thread.Sleep(1000)

        ' Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData(localSlot).ToString())
    End Sub

End Class

Remarques

Important

.NET Framework fournit deux mécanismes pour l’utilisation du stockage local des threads (TLS) : les champs statiques relatifs à un thread (autrement dit, les champs marqués avec l' ThreadStaticAttribute attribut) et les emplacements de données. Les champs statiques relatifs à un thread offrent de meilleures performances que les emplacements de données et activent la vérification de type au moment de la compilation. pour plus d’informations sur l’utilisation de TLS, consultez Thread Local Stockage : Thread-Relative les champs statiques et les emplacements de données.

Les threads utilisent un mécanisme de mémoire de stockage local pour stocker des données spécifiques aux threads. Le common language runtime alloue un groupe de magasins de données à plusieurs emplacements à chaque processus lors de sa création. Le thread peut allouer un emplacement de données dans le magasin de données, stocker et récupérer une valeur de données dans l’emplacement, puis libérer l’emplacement en vue de sa réutilisation après l’expiration du thread. Les emplacements de données sont uniques par thread. Aucun autre thread (pas même un thread enfant) ne peut obtenir ces données.

Notes

GetData est une Shared méthode qui s’applique toujours au thread en cours d’exécution, même si vous l’appelez à l’aide d’une variable qui fait référence à un autre thread. Pour éviter toute confusion, utilisez le nom de la classe lors de l’appel de Shared méthodes : Dim test As Object = Thread.GetData(testSlot) .

S’applique à

Voir aussi