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

設定される値です。

このセクションには、2 つのコード例が含まれています。 最初の例では、 属性で ThreadStaticAttribute マークされているフィールドを使用して、スレッド固有の情報を保持する方法を示します。 2 番目の例は、データ スロットを使用して同じことを行う方法を示しています。

最初の例

次の例は、 で ThreadStaticAttribute マークされているフィールドを使用して、スレッド固有の情報を保持する方法を示しています。 この手法は、2 番目の例に示されている手法よりも優れたパフォーマンスを提供します。

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
 */
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

2 番目の例

次の例では、名前付きデータ スロットを使用してスレッド固有の情報を格納する方法を示します。

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);
        }
    }
}
open System
open System.Threading

module Slot =
    let private randomGenerator = Random()

    let slotTest () =
        // Set random data in each thread's data slot.
        let slotData = randomGenerator.Next(1, 200)
        let threadId = Thread.CurrentThread.ManagedThreadId

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

        // Show what was saved in the thread's data slot.
        printfn $"Data stored in thread_{threadId}'s data slot: {slotData, 3}"

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

        let newSlotData = Thread.GetData(Thread.GetNamedDataSlot "Random") :?> int

        if newSlotData = slotData then
            printfn $"Data in thread_{threadId}'s data slot is still: {newSlotData, 3}"
        else
            printfn $"Data in thread_{threadId}'s data slot changed to: {newSlotData, 3}"

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

Thread.Sleep 2000

for tread in newThreads do
    tread.Join()
    printfn $"Thread_{tread.ManagedThreadId} finished."
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) を使用するための 2 つのメカニズム (スレッド相対静的フィールド (つまり、 属性でThreadStaticAttributeマークされているフィールド) とデータ スロット) が提供されます。 スレッド相対静的フィールドは、データ スロットよりもはるかに優れたパフォーマンスを提供し、コンパイル時の型チェックを有効にします。 TLS の使用の詳細については、「 スレッド ローカル ストレージ: 静的フィールドとデータ スロットのThread-Relative」を参照してください。

スレッドは、ローカル ストア メモリ メカニズムを使用してスレッド固有のデータを格納します。 共通言語ランタイムは、作成時にマルチスロット データ ストア配列を各プロセスに割り当てます。 スレッドは、データ ストアにデータ スロットを割り当て、スロットにデータ値を格納および取得し、スレッド プロシージャが終了し、オブジェクトがガベージ コレクションによって再利用された後に再利用できるようにスロットを Thread 解放できます。 データ スロットはスレッドごとに一意です。 他のスレッド (子スレッドでもない) は、そのデータを取得できません。

Note

SetData は、別の Shared スレッドを参照する変数を使用して呼び出した場合でも、常に現在実行中のスレッドに適用されるメソッドです。 混乱を避けるには、 メソッドを呼び出Sharedすときにクラス名を使用します。 Thread.SetData(testSlot, "test data")

適用対象

こちらもご覧ください