ThreadLocal<T> Classe

Definição

Fornece armazenamento local de dados em threads.

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 Genérico

T

Especifica o tipo de dados armazenados por thread.

Herança
ThreadLocal<T>
Implementações

Exemplos

O exemplo a seguir mostra como 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)

Construtores

Name Description
ThreadLocal<T>()

Inicializa a ThreadLocal<T> instância.

ThreadLocal<T>(Boolean)

Inicializa a ThreadLocal<T> instância e especifica se todos os valores são acessíveis a partir de qualquer thread.

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

Inicializa a ThreadLocal<T> instância com a função especificada valueFactory e um flag que indica se todos os valores são acessíveis a partir de qualquer thread.

ThreadLocal<T>(Func<T>)

Inicializa a ThreadLocal<T> instância com a função especificada valueFactory .

Propriedades

Name Description
IsValueCreated

Obtém se Value está inicializado na thread atual.

Value

Obtém ou define o valor desta instância para o thread atual.

Values

Obtém uma lista contendo os valores armazenados por todas as threads que acederam a esta instância.

Métodos

Name Description
Dispose()

Liberta todos os recursos usados pela instância atual da ThreadLocal<T> classe.

Dispose(Boolean)

Liberta os recursos usados por esta ThreadLocal<T> instância.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
Finalize()

Liberta os recursos usados por esta ThreadLocal<T> instância.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Cria e devolve uma representação de string desta instância para o thread atual.

Aplica-se a

Segurança de Thread

Com exceção de Dispose(), todos os membros públicos e protegidos de ThreadLocal<T> são seguros para threads e podem ser usados simultaneamente a partir de múltiplos threads. O valor devolvido para as Value propriedades e IsValueCreated é específico para o thread onde a propriedade é acedida.

Ver também