Thread.AllocateDataSlot 메서드

정의

모든 스레드에 명명되지 않은 데이터 슬롯을 할당합니다. 성능을 향상시키려면 ThreadStaticAttribute 특성으로 표시된 필드를 대신 사용합니다.

public:
 static LocalDataStoreSlot ^ AllocateDataSlot();
public static LocalDataStoreSlot AllocateDataSlot ();
static member AllocateDataSlot : unit -> LocalDataStoreSlot
Public Shared Function AllocateDataSlot () As LocalDataStoreSlot

반환

모든 스레드에 할당된 명명된 데이터 슬롯입니다.

예제

이 섹션에는 두 코드 예제가 있습니다. 첫 번째 예제에서는 특성으로 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
 */
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 namespace System;
using namespace System::Threading;
ref class Slot
{
private:
   static Random^ randomGenerator;
   static LocalDataStoreSlot^ localSlot;
   static Slot()
   {
      randomGenerator = gcnew 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() );
   }

};

int main()
{
   array<Thread^>^newThreads = gcnew array<Thread^>(4);
   for ( int i = 0; i < newThreads->Length; i++ )
   {
      newThreads[ i ] = gcnew Thread( gcnew ThreadStart( &Slot::SlotTest ) );
      newThreads[ i ]->Start();

   }
}
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

설명

중요

.NET Framework는 TLS(스레드 로컬 스토리지)를 사용하는 두 가지 메커니즘, 즉 스레드 상대 정적 필드(즉, ThreadStaticAttribute 특성으로 표시된 필드) 및 데이터 슬롯을 제공합니다. 스레드 상대 정적 필드는 데이터 슬롯보다 훨씬 더 나은 성능을 제공하고 컴파일 시간 형식 검사를 사용하도록 설정합니다. TLS 사용에 대한 자세한 내용은 스레드 로컬 스토리지: 스레드 상대 정적 필드 및 데이터 슬롯을 참조하세요.

슬롯은 모든 스레드에 할당됩니다.

스레드는 로컬 저장소 메모리 메커니즘을 사용하여 스레드별 데이터를 저장합니다. 공용 언어 런타임은 다중 슬롯 데이터 저장소 배열을 만들 때 각 프로세스에 할당합니다. 스레드는 데이터 저장소에 데이터 슬롯을 할당하고, 슬롯에 데이터 값을 저장 및 검색하고, 스레드가 만료된 후 다시 사용할 수 있는 슬롯을 해제할 수 있습니다. 데이터 슬롯은 스레드당 고유합니다. 다른 스레드(자식 스레드도 아님)는 해당 데이터를 가져올 수 없습니다.

적용 대상

추가 정보