Thread.SetData(LocalDataStoreSlot, Object) 方法

定义

在当前正在运行的线程上为此线程的当前域在指定槽中设置数据。 为了提高性能,请改用用 ThreadStaticAttribute 属性标记的字段。

public:
 static void SetData(LocalDataStoreSlot ^ slot, System::Object ^ data);
public static void SetData (LocalDataStoreSlot slot, object? data);
public static void SetData (LocalDataStoreSlot slot, object data);
static member SetData : LocalDataStoreSlot * obj -> unit
Public Shared Sub SetData (slot As LocalDataStoreSlot, data As Object)

参数

slot
LocalDataStoreSlot

在其中设置值的 LocalDataStoreSlot

data
Object

要设置的值。

示例

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

第一个示例

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

using namespace System;
using namespace System::Threading;

ref class ThreadData
{
private:
   [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 );
   }
};

int main()
{
   for ( int i = 0; i < 3; i++ )
   {
      Thread^ newThread = 
          gcnew Thread( gcnew ThreadStart( 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
 */
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
 */
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 namespace System;
using namespace System::Threading;

ref class Slot
{
private:
    static Random^ randomGenerator = gcnew Random();

public:
    static void SlotTest()
    {
        // Set random data in each thread's data slot.
        int slotData = randomGenerator->Next(1, 200);
        int threadId = Thread::CurrentThread->ManagedThreadId;

        Thread::SetData(
            Thread::GetNamedDataSlot("Random"),
            slotData);

        // Show what was saved in the thread's data slot.
        Console::WriteLine("Data stored in thread_{0}'s data slot: {1,3}",
            threadId, slotData);

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

        int newSlotData =
            (int)Thread::GetData(Thread::GetNamedDataSlot("Random"));

        if (newSlotData == slotData)
        {
            Console::WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
                threadId, newSlotData);
        }
        else
        {
            Console::WriteLine("Data in thread_{0}'s data slot changed to: {1,3}",
                threadId, newSlotData);
        }
    }
};

ref class Test
{
public:
    static void Main()
    {
        array<Thread^>^ newThreads = gcnew array<Thread^>(4);
        int i;
        for (i = 0; i < newThreads->Length; i++)
        {
            newThreads[i] =
                gcnew Thread(gcnew ThreadStart(&Slot::SlotTest));
            newThreads[i]->Start();
        }
        Thread::Sleep(2000);
        for (i = 0; i < newThreads->Length; i++)
        {
            newThreads[i]->Join();
            Console::WriteLine("Thread_{0} finished.",
                newThreads[i]->ManagedThreadId);
        }
    }
};

int main()
{
    Test::Main();
}
using System;
using System.Threading;

class Test
{
    public static void Main()
    {
        Thread[] newThreads = new Thread[4];
        int i;
        for (i = 0; i < newThreads.Length; i++)
        {
            newThreads[i] =
                new Thread(new ThreadStart(Slot.SlotTest));
            newThreads[i].Start();
        }
        Thread.Sleep(2000);
        for (i = 0; i < newThreads.Length; i++)
        {
            newThreads[i].Join();
            Console.WriteLine("Thread_{0} finished.",
                newThreads[i].ManagedThreadId);
        }
    }
}

class Slot
{
    private static Random randomGenerator = new Random();

    public static void SlotTest()
    {
        // Set random data in each thread's data slot.
        int slotData = randomGenerator.Next(1, 200);
        int threadId = Thread.CurrentThread.ManagedThreadId;

        Thread.SetData(
            Thread.GetNamedDataSlot("Random"),
            slotData);

        // Show what was saved in the thread's data slot.
        Console.WriteLine("Data stored in thread_{0}'s data slot: {1,3}",
            threadId, slotData);

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

        int newSlotData =
            (int)Thread.GetData(Thread.GetNamedDataSlot("Random"));

        if (newSlotData == slotData)
        {
            Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
                threadId, newSlotData);
        }
        else
        {
            Console.WriteLine("Data in thread_{0}'s data slot changed to: {1,3}",
                threadId, newSlotData);
        }
    }
}
Imports System.Threading

Class Test
    Public Shared Sub Main()
        Dim newThreads(3) As Thread
        Dim i As Integer
        For i = 0 To newThreads.Length - 1
            newThreads(i) = _
                New Thread(New ThreadStart(AddressOf Slot.SlotTest))
            newThreads(i).Start()
        Next i
        Thread.Sleep(2000)
        For i = 0 To newThreads.Length - 1
            newThreads(i).Join()
            Console.WriteLine("Thread_{0} finished.", _
                newThreads(i).ManagedThreadId)
        Next i
    End Sub
End Class

Class Slot
    Private Shared randomGenerator As New Random()

    Public Shared Sub SlotTest()
        ' Set random data in each thread's data slot.
        Dim slotData As Integer = randomGenerator.Next(1, 200)
        Dim threadId As Integer = Thread.CurrentThread.ManagedThreadId

        Thread.SetData(
            Thread.GetNamedDataSlot("Random"),
            slotData)

        ' Show what was saved in the thread's data slot.
        Console.WriteLine("Data stored in thread_{0}'s data slot: {1,3}",
            threadId, slotData)

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

        Dim newSlotData As Integer = _
            CType(Thread.GetData(Thread.GetNamedDataSlot("Random")), Integer)

        If newSlotData = slotData Then
            Console.WriteLine("Data in thread_{0}'s data slot is still: {1,3}",
                threadId, newSlotData)
        Else
            Console.WriteLine("Data in thread_{0}'s data slot changed to: {1,3}",
                threadId, newSlotData)
        End If
    End Sub
End Class

注解

重要

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

线程使用本地存储内存机制来存储特定于线程的数据。 公共语言运行时在创建每个进程时,会向每个进程分配一个多槽数据存储数组。 线程可以在数据存储中分配数据槽,在槽中存储和检索数据值,并在线程过程结束后释放该槽供重复使用,并且对象已被垃圾回收 Thread 回收。 每个线程的数据槽是唯一的。 其他线程 (子线程) 获取该数据。

备注

SetData 是始终应用于当前正在执行的线程的方法,即使你使用引用另一个线程的变量 Shared 调用它。 为了避免混淆,在调用 方法时请使用类 SharedThread.SetData(testSlot, "test data") :。

适用于

另请参阅