Thread.GetData(LocalDataStoreSlot) Thread.GetData(LocalDataStoreSlot) Thread.GetData(LocalDataStoreSlot) Thread.GetData(LocalDataStoreSlot) Method

Definición

Recupera el valor de la ranura especificada en el subproceso actual, dentro del dominio actual del subproceso.Retrieves the value from the specified slot on the current thread, within the current thread's current domain. Para mejorar el rendimiento, en su lugar use campos marcados con el atributo ThreadStaticAttribute.For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

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

Parámetros

slot
LocalDataStoreSlot LocalDataStoreSlot LocalDataStoreSlot LocalDataStoreSlot

La LocalDataStoreSlot de donde se va a obtener el valor.The LocalDataStoreSlot from which to get the value.

Devoluciones

El valor recuperado.The retrieved value.

Ejemplos

Esta sección contiene dos ejemplos de código.This section contains two code examples. En el primer ejemplo se muestra cómo usar un campo marcado con el atributo ThreadStaticAttribute para almacenar información específica del subproceso.The first example shows how to use a field that is marked with the ThreadStaticAttribute attribute to hold thread-specific information. En el segundo ejemplo se muestra cómo usar una ranura de datos para hacer lo mismo.The second example shows how to use a data slot to do the same thing.

Primer ejemploFirst Example

En el ejemplo siguiente se muestra cómo usar un campo marcado con ThreadStaticAttribute para almacenar información específica del subproceso.The following example shows how to use a field that is marked with ThreadStaticAttribute to hold thread-specific information. Esta técnica proporciona un mejor rendimiento que la técnica que se muestra en el segundo ejemplo.This technique provides better performance than the technique that is shown in the second example.

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
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

Segundo ejemploSecond Example

En el ejemplo siguiente se muestra cómo usar una ranura de datos para almacenar información específica del subproceso.The following example demonstrates how to use a data slot to store thread-specific information.

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
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

Comentarios

Importante

El .NET Framework proporciona dos mecanismos para usar el almacenamiento local de subprocesos (TLS): campos estáticos relacionados con subprocesos (es decir ThreadStaticAttribute , campos marcados con el atributo) y ranuras de datos.The .NET Framework provides two mechanisms for using thread local storage (TLS): thread-relative static fields (that is, fields that are marked with the ThreadStaticAttribute attribute) and data slots. Los campos estáticos relacionados con subprocesos proporcionan un rendimiento mucho mejor que las ranuras de datos y habilitan la comprobación de tipos en tiempo de compilación.Thread-relative static fields provide much better performance than data slots, and enable compile-time type checking. Para obtener más información sobre el uso de TLS, vea almacenamiento local para el subproceso: Campos estáticos relacionados con subprocesosy ranuras de datos.For more information about using TLS, see Thread Local Storage: Thread-Relative Static Fields and Data Slots.

Los subprocesos usan un mecanismo de memoria del almacén local para almacenar datos específicos del subproceso.Threads use a local store memory mechanism to store thread-specific data. El Common Language Runtime asigna una matriz de almacén de datos de varias ranuras a cada proceso cuando se crea.The common language runtime allocates a multi-slot data store array to each process when it is created. El subproceso puede asignar una ranura de datos en el almacén de datos, almacenar y recuperar un valor de datos en la ranura y liberar la ranura para su reutilización después de que expire el subproceso.The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Las ranuras de datos son únicas por subproceso.Data slots are unique per thread. Ningún otro subproceso (ni siquiera un subproceso secundario) puede obtener esos datos.No other thread (not even a child thread) can get that data.

Nota

GetDataes un Shared método que siempre se aplica al subproceso que se está ejecutando actualmente, aunque se llame mediante una variable que haga referencia a otro subproceso.GetData is a Shared method that always applies to the currently executing thread, even if you call it using a variable that refers to another thread. Para evitar confusiones, use el nombre de clase Shared cuando llame Dim test As Object = Thread.GetData(testSlot)a los métodos:.To avoid confusion, use the class name when calling Shared methods: Dim test As Object = Thread.GetData(testSlot).

Se aplica a

Consulte también: