ThreadLocal<T> ThreadLocal<T> ThreadLocal<T> ThreadLocal<T> Class

Definición

Proporciona almacenamiento local de los datos de un subproceso.Provides thread-local storage of data.

generic <typename T>
public ref class ThreadLocal : IDisposable
public class ThreadLocal<T> : IDisposable
type ThreadLocal<'T> = class
    interface IDisposable
Public Class ThreadLocal(Of T)
Implements IDisposable

Parámetros de tipo

T

Especifica el tipo de datos almacenados por subproceso.Specifies the type of data stored per-thread.

Herencia
ThreadLocal<T>ThreadLocal<T>ThreadLocal<T>ThreadLocal<T>
Implementaciones

Ejemplos

En el siguiente ejemplo se muestra cómo usar ThreadLocal<T>:The following example shows how to use ThreadLocal<T>:

using System;
using System.Threading;
using System.Threading.Tasks;

class ThreadLocalDemo
{
    
        // Demonstrates:
        //      ThreadLocal(T) constructor
        //      ThreadLocal(T).Value
        //      One usage of ThreadLocal(T)
        static void Main()
        {
            // Thread-Local variable that yields a name for a thread
            ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>
            {
                return "Thread" + Thread.CurrentThread.ManagedThreadId;
            });

            // Action that prints out ThreadName for the current thread
            Action action = () =>
            {
                // If ThreadName.IsValueCreated is true, it means that we are not the
                // first action to run on this thread.
                bool repeat = ThreadName.IsValueCreated;

                Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : "");
            };

            // Launch eight of them.  On 4 cores or less, you should see some repeat ThreadNames
            Parallel.Invoke(action, action, action, action, action, action, action, action);

            // Dispose when you are done
            ThreadName.Dispose();
        }
}
// This multithreading example can produce different outputs for each 'action' invocation and will vary with each run.
// Therefore, the example output will resemble but may not exactly match the following output (from a 4 core processor):
// ThreadName = Thread5 
// ThreadName = Thread6 
// ThreadName = Thread4 
// ThreadName = Thread6 (repeat)
// ThreadName = Thread1 
// ThreadName = Thread4 (repeat)
// ThreadName = Thread7 
// ThreadName = Thread5 (repeat)
Imports System.Threading
Imports System.Threading.Tasks

Module ThreadLocalDemo

    ' Demonstrates:
    ' ThreadLocal(T) constructor
    ' ThreadLocal(T).Value
    ' One usage of ThreadLocal(T)
    Sub Main()
        ' Thread-Local variable that yields a name for a thread
        Dim ThreadName As New ThreadLocal(Of String)(
            Function()
                Return "Thread" & Thread.CurrentThread.ManagedThreadId
            End Function)

        ' Action that prints out ThreadName for the current thread
        Dim action As Action =
            Sub()
                ' If ThreadName.IsValueCreated is true, it means that we are not the
                ' first action to run on this thread.
                Dim repeat As Boolean = ThreadName.IsValueCreated

                Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, If(repeat, "(repeat)", ""))
            End Sub

        ' Launch eight of them. On 4 cores or less, you should see some repeat ThreadNames
        Parallel.Invoke(action, action, action, action, action, action, action, action)

        ' Dispose when you are done
        ThreadName.Dispose()
    End Sub
End Module
' This multithreading example can produce different outputs for each 'action' invocation and will vary with each run.
' Therefore, the example output will resemble but may not exactly match the following output (from a 4 core processor):
' ThreadName = Thread5 
' ThreadName = Thread6 
' ThreadName = Thread4 
' ThreadName = Thread6 (repeat)
' ThreadName = Thread1 
' ThreadName = Thread4 (repeat)
' ThreadName = Thread7 
' ThreadName = Thread5 (repeat)    

Constructores

ThreadLocal<T>() ThreadLocal<T>() ThreadLocal<T>() ThreadLocal<T>()

Inicializa la instancia ThreadLocal<T>.Initializes the ThreadLocal<T> instance.

ThreadLocal<T>(Boolean) ThreadLocal<T>(Boolean) ThreadLocal<T>(Boolean) ThreadLocal<T>(Boolean)

Inicializa la instancia ThreadLocal<T> y especifica si todos los valores son accesibles desde cualquier subproceso.Initializes the ThreadLocal<T> instance and specifies whether all values are accessible from any thread.

ThreadLocal<T>(Func<T>) ThreadLocal<T>(Func<T>) ThreadLocal<T>(Func<T>) ThreadLocal<T>(Func<T>)

Inicializa una instancia de ThreadLocal<T> con la función especificada por el parámetro valueFactory.Initializes the ThreadLocal<T> instance with the specified valueFactory function.

ThreadLocal<T>(Func<T>, Boolean) ThreadLocal<T>(Func<T>, Boolean) ThreadLocal<T>(Func<T>, Boolean) ThreadLocal<T>(Func<T>, Boolean)

Inicializa la instancia ThreadLocal<T> con la función valueFactory especificada y una marca que indica si todos los valores son accesibles desde cualquier subproceso.Initializes the ThreadLocal<T> instance with the specified valueFactory function and a flag that indicates whether all values are accessible from any thread.

Propiedades

IsValueCreated IsValueCreated IsValueCreated IsValueCreated

Obtiene un valor que indica si Value se inicializa en el subproceso actual.Gets whether Value is initialized on the current thread.

Value Value Value Value

Obtiene o establece el valor de esta instancia del subproceso actual.Gets or sets the value of this instance for the current thread.

Values Values Values Values

Obtiene una lista de todos los valores almacenados actualmente por todos los subprocesos que han tenido acceso a esta instancia.Gets a list for all of the values currently stored by all of the threads that have accessed this instance.

Métodos

Dispose() Dispose() Dispose() Dispose()

Libera todos los recursos usados por la instancia actual de la clase ThreadLocal<T>.Releases all resources used by the current instance of the ThreadLocal<T> class.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos que usa la instancia ThreadLocal<T>.Releases the resources used by this ThreadLocal<T> instance.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Libera los recursos que usa la instancia ThreadLocal<T>.Releases the resources used by this ThreadLocal<T> instance.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Crea y devuelve una representación de cadena de esta instancia del subproceso actual.Creates and returns a string representation of this instance for the current thread.

Se aplica a

Seguridad para subprocesos

A excepción de Dispose(), todos los miembros públicos y protegidos de ThreadLocal<T> son seguros para subprocesos y se pueden usar simultáneamente desde varios subprocesos.With the exception of Dispose(), all public and protected members of ThreadLocal<T> are thread-safe and may be used concurrently from multiple threads. El valor devuelto para Value las IsValueCreated propiedades y es específico para el subproceso en el que se tiene acceso a la propiedad.The value returned for the Value and IsValueCreated properties is specific for the thread on which the property is accessed.

Consulte también: