Thread.GetData(LocalDataStoreSlot) 方法

定义

从当前线程的当前域中的指定槽中检索值。 为了获得更好的性能,请改用带有属性标记的 ThreadStaticAttribute 字段。

public:
 static System::Object ^ GetData(LocalDataStoreSlot ^ slot);
public static object GetData(LocalDataStoreSlot slot);
static member GetData : LocalDataStoreSlot -> obj
Public Shared Function GetData (slot As LocalDataStoreSlot) As Object

参数

slot
LocalDataStoreSlot

LocalDataStoreSlot 中获取值。

返回

检索到的值。

示例

本部分包含两个代码示例。 第一个示例演示如何使用带有 ThreadStaticAttribute 属性标记的字段来保存特定于线程的信息。 第二个示例演示如何使用数据槽执行相同的操作。

第一个示例

以下示例演示如何使用标记 ThreadStaticAttribute 的字段来保存特定于线程的信息。 此技术比第二个示例中所示的技术提供更好的性能。

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        for(int i = 0; i < 3; i++)
        {
            Thread newThread = new Thread(ThreadData.ThreadStaticDemo);
            newThread.Start();
        }
    }
}

class ThreadData
{
    [ThreadStatic]
    static int threadSpecificData;

    public static void ThreadStaticDemo()
    {
        // Store the managed thread id for each thread in the static
        // variable.
        threadSpecificData = Thread.CurrentThread.ManagedThreadId;
      
        // Allow other threads time to execute the same code, to show
        // that the static data is unique to each thread.
        Thread.Sleep( 1000 );

        // Display the static data.
        Console.WriteLine( "Data for managed thread {0}: {1}", 
            Thread.CurrentThread.ManagedThreadId, threadSpecificData );
    }
}

/* This code example produces output similar to the following:

Data for managed thread 4: 4
Data for managed thread 5: 5
Data for managed thread 3: 3
 */
open System
open System.Threading

type ThreadData() =
    // Create a static variable to hold the data for each thread.
    [<ThreadStatic; DefaultValue>]
    static val mutable private threadSpecificData : int

    static member ThreadStaticDemo() =
        // Store the managed thread id for each thread in the static
        // variable.
        ThreadData.threadSpecificData <- Thread.CurrentThread.ManagedThreadId
        
        // Allow other threads time to execute the same code, to show
        // that the static data is unique to each thread.
        Thread.Sleep 1000

        // Display the static data.
        printfn $"Data for managed thread {Thread.CurrentThread.ManagedThreadId}: {ThreadData.threadSpecificData}" 

for i = 0 to 2 do 
    let newThread = Thread ThreadData.ThreadStaticDemo
    newThread.Start()

// This code example produces output similar to the following:
//       Data for managed thread 4: 4
//       Data for managed thread 5: 5
//       Data for managed thread 3: 3
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()

        For i As Integer = 1 To 3
            Dim newThread As New Thread(AddressOf ThreadData.ThreadStaticDemo)
            newThread.Start()
        Next i

    End Sub

End Class

Class ThreadData

    <ThreadStatic> _
    Shared threadSpecificData As Integer

    Shared Sub ThreadStaticDemo()

        ' Store the managed thread id for each thread in the static
        ' variable.
        threadSpecificData = Thread.CurrentThread.ManagedThreadId
      
        ' Allow other threads time to execute the same code, to show
        ' that the static data is unique to each thread.
        Thread.Sleep( 1000 )

        ' Display the static data.
        Console.WriteLine( "Data for managed thread {0}: {1}", _
            Thread.CurrentThread.ManagedThreadId, threadSpecificData )

    End Sub

End Class

' This code example produces output similar to the following:
'
'Data for managed thread 4: 4
'Data for managed thread 5: 5
'Data for managed thread 3: 3

第二个示例

以下示例演示如何使用数据槽来存储特定于线程的信息。

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        Thread[] newThreads = new Thread[4];
        for(int i = 0; i < newThreads.Length; i++)
        {
            newThreads[i] = new Thread(
                new ThreadStart(Slot.SlotTest));
            newThreads[i].Start();
        }
    }
}

class Slot
{
    static Random randomGenerator;
    static LocalDataStoreSlot localSlot;

    static Slot()
    {
        randomGenerator = new Random();
        localSlot = Thread.AllocateDataSlot();
    }

    public static void SlotTest()
    {
        // Set different data in each thread's data slot.
        Thread.SetData(localSlot, randomGenerator.Next(1, 200));

        // Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(localSlot).ToString());

        // Allow other threads time to execute SetData to show
        // that a thread's data slot is unique to the thread.
        Thread.Sleep(1000);

        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", 
            AppDomain.GetCurrentThreadId().ToString(),
            Thread.GetData(localSlot).ToString());
    }
}
open System
open System.Threading

module Slot =
    let randomGenerator = Random()
    let localSlot = Thread.AllocateDataSlot()


    let slotTest () =
        // Set different data in each thread's data slot.
        Thread.SetData(localSlot, randomGenerator.Next(1, 200))

        // Write the data from each thread's data slot.
        printfn $"Data in thread_{AppDomain.GetCurrentThreadId()}'s data slot: {Thread.GetData localSlot, 3}"

        // Allow other threads time to execute SetData to show
        // that a thread's data slot is unique to the thread.
        Thread.Sleep 1000

        printfn $"Data in thread_{AppDomain.GetCurrentThreadId()}'s data slot: {Thread.GetData localSlot, 3}"

let newThreads =
    [| for _ = 0 to 3 do
           let thread = Thread Slot.slotTest
           thread.Start()
           thread |]
Imports System.Threading

Class Test

    <MTAThread> _
    Shared Sub Main()
        Dim newThreads(3) As Thread
        For i As Integer = 0 To newThreads.Length - 1
            newThreads(i) = New Thread(AddressOf Slot.SlotTest)
            newThreads(i).Start()
        Next i
    End Sub

End Class

Public Class Slot

    Shared randomGenerator As Random
    Shared localSlot As LocalDataStoreSlot

    Shared Sub New()
        randomGenerator = new Random()
        localSlot = Thread.AllocateDataSlot()
    End Sub

    Shared Sub SlotTest()

        ' Set different data in each thread's data slot.
        Thread.SetData(localSlot, randomGenerator.Next(1, 200))

        ' Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData(localSlot).ToString())

        ' Allow other threads time to execute SetData to show
        ' that a thread's data slot is unique to the thread.
        Thread.Sleep(1000)

        ' Write the data from each thread's data slot.
        Console.WriteLine("Data in thread_{0}'s data slot: {1,3}", _
            AppDomain.GetCurrentThreadId().ToString(), _
            Thread.GetData(localSlot).ToString())
    End Sub

End Class

注解

Important

.NET Framework 提供了两种机制,用于使用线程本地存储(TLS):线程相对静态字段(即使用 ThreadStaticAttribute 属性标记的字段)和数据槽。 相对于线程的静态字段比数据槽提供更好的性能,并启用编译时类型检查。 有关使用 TLS 的详细信息,请参阅 线程本地存储:Thread-Relative 静态字段和数据槽

线程使用本地存储内存机制来存储特定于线程的数据。 公共语言运行时在创建时将多槽数据存储数组分配给每个进程。 线程可以在数据存储中分配数据槽,在槽中存储和检索数据值,并在线程过期后释放槽以供重复使用。 每个线程的数据槽是唯一的。 任何其他线程(甚至子线程)都无法获取该数据。

Note

GetData 是一种 Shared 始终应用于当前正在执行的线程的方法,即使你使用引用另一个线程的变量调用它。 为避免混淆,在调用 Shared 方法时使用类名: Dim test As Object = Thread.GetData(testSlot)

适用于

另请参阅