ThreadLocal<T> Clase
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Proporciona almacenamiento local de los datos de un subproceso.
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
- T
Especifica el tipo de datos almacenados por subproceso.
- Herencia
-
ThreadLocal<T>
- Implementaciones
En el siguiente ejemplo se muestra cómo usar 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)
Thread |
Inicializa la instancia ThreadLocal<T>. |
Thread |
Inicializa la instancia ThreadLocal<T> y especifica si todos los valores son accesibles desde cualquier subproceso. |
Thread |
Inicializa una instancia de ThreadLocal<T> con la función especificada por el parámetro |
Thread |
Inicializa la instancia ThreadLocal<T> con la función |
Is |
Obtiene un valor que indica si Value se inicializa en el subproceso actual. |
Value |
Obtiene o establece el valor de esta instancia del subproceso actual. |
Values |
Obtiene una lista que contiene los valores almacenados por todos los subprocesos a los que ha accedido esta instancia. |
Dispose() |
Libera todos los recursos usados por la instancia actual de la clase ThreadLocal<T>. |
Dispose(Boolean) |
Libera los recursos que usa la instancia ThreadLocal<T>. |
Equals(Object) |
Determina si el objeto especificado es igual que el objeto actual. (Heredado de Object) |
Finalize() |
Libera los recursos que usa la instancia ThreadLocal<T>. |
Get |
Sirve como la función hash predeterminada. (Heredado de Object) |
Get |
Obtiene el Type de la instancia actual. (Heredado de Object) |
Memberwise |
Crea una copia superficial del Object actual. (Heredado de Object) |
To |
Crea y devuelve una representación de cadena de esta instancia del subproceso actual. |
Producto | Versiones |
---|---|
.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 |
.NET Framework | 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 |
.NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1 |
UWP | 10.0 |
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. El valor devuelto para las Value propiedades y IsValueCreated es específico para el subproceso en el que se tiene acceso a la propiedad .