ThreadLocal<T> 类

定义

提供数据的线程本地存储。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

类型参数

T

指定按线程存储的数据类型。Specifies the type of data stored per-thread.

继承
ThreadLocal<T>
实现

示例

下面的示例演示如何使用 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)    

构造函数

ThreadLocal<T>()

初始化 ThreadLocal<T> 实例。Initializes the ThreadLocal<T> instance.

ThreadLocal<T>(Boolean)

初始化 ThreadLocal<T> 实例并指定是否可从任意线程访问所有值。Initializes the ThreadLocal<T> instance and specifies whether all values are accessible from any thread.

ThreadLocal<T>(Func<T>)

使用指定的 ThreadLocal<T> 函数初始化 valueFactory 实例。Initializes the ThreadLocal<T> instance with the specified valueFactory function.

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

使用指定的 ThreadLocal<T> 函数和指示是否可从任意线程访问所有值的标志初始化 valueFactory 实例。Initializes the ThreadLocal<T> instance with the specified valueFactory function and a flag that indicates whether all values are accessible from any thread.

属性

IsValueCreated

获取是否在当前线程上初始化 ValueGets whether Value is initialized on the current thread.

Value

获取或设置当前线程的此实例的值。Gets or sets the value of this instance for the current thread.

Values

获取当前由已经访问此实例的所有线程存储的所有值的列表。Gets a list for all of the values currently stored by all of the threads that have accessed this instance.

方法

Dispose()

释放 ThreadLocal<T> 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the ThreadLocal<T> class.

Dispose(Boolean)

释放该 ThreadLocal<T> 实例使用的资源。Releases the resources used by this ThreadLocal<T> instance.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Finalize()

释放该 ThreadLocal<T> 实例使用的资源。Releases the resources used by this ThreadLocal<T> instance.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

创建并返回当前线程的此实例的字符串表示形式。Creates and returns a string representation of this instance for the current thread.

适用于

线程安全性

除了 Dispose()之外,ThreadLocal<T> 的所有公共成员和受保护成员都是线程安全的,可从多个线程并发使用。With the exception of Dispose(), all public and protected members of ThreadLocal<T> are thread-safe and may be used concurrently from multiple threads. ValueIsValueCreated 属性返回的值特定于在其上访问该属性的线程。The value returned for the Value and IsValueCreated properties is specific for the thread on which the property is accessed.

另请参阅