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

Définition

Fournit le stockage local des données de thread.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

Paramètres de type

T

Spécifie le type de données stockées par thread.Specifies the type of data stored per-thread.

Héritage
ThreadLocal<T>ThreadLocal<T>ThreadLocal<T>ThreadLocal<T>
Implémente

Exemples

L'exemple suivant montre comment utiliser 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)    

Constructeurs

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

Initialise l’instance ThreadLocal<T>.Initializes the ThreadLocal<T> instance.

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

Initialise l’instance ThreadLocal<T> et spécifie si toutes les valeurs sont accessibles à partir de n’importe quel thread.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>)

Initialise l'instance de ThreadLocal<T> avec la fonction valueFactory spécifiée.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)

Initialise l’instance ThreadLocal<T> avec la fonction valueFactory spécifiée et un indicateur qui indique si toutes les valeurs sont accessibles à partir de n’importe quel thread.Initializes the ThreadLocal<T> instance with the specified valueFactory function and a flag that indicates whether all values are accessible from any thread.

Propriétés

IsValueCreated IsValueCreated IsValueCreated IsValueCreated

Obtient une valeur qui indique si Value est initialisé sur le thread actuel.Gets whether Value is initialized on the current thread.

Value Value Value Value

Obtient ou définit la valeur de cette instance pour le thread actuel.Gets or sets the value of this instance for the current thread.

Values Values Values Values

Obtient une liste de toutes les valeurs actuellement stockées par tous les threads qui ont accès à cette instance.Gets a list for all of the values currently stored by all of the threads that have accessed this instance.

Méthodes

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

Libère toutes les ressources utilisées par l'instance actuelle de la classe ThreadLocal<T>.Releases all resources used by the current instance of the ThreadLocal<T> class.

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

Libère les ressources utilisées par cette instance de ThreadLocal<T>.Releases the resources used by this ThreadLocal<T> instance.

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

Détermine si l'objet spécifié est identique à l'objet actuel.Determines whether the specified object is equal to the current object.

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

Libère les ressources utilisées par cette instance de ThreadLocal<T>.Releases the resources used by this ThreadLocal<T> instance.

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

Fait office de fonction de hachage par défaut.Serves as the default hash function.

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

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

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

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

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

Crée et retourne une représentation sous forme de chaîne de cette instance pour le thread actuel.Creates and returns a string representation of this instance for the current thread.

S’applique à

Cohérence de thread

À l’exception de Dispose(), tous les membres publics et protégés ThreadLocal<T> de sont thread-safe et peuvent être utilisés simultanément à partir de plusieurs threads.With the exception of Dispose(), all public and protected members of ThreadLocal<T> are thread-safe and may be used concurrently from multiple threads. La valeur retournée pour Value les IsValueCreated propriétés et est spécifique au thread sur lequel la propriété est accédée.The value returned for the Value and IsValueCreated properties is specific for the thread on which the property is accessed.

Voir aussi