Thread.AllocateNamedDataSlot(String) 메서드

정의

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

public:
 static LocalDataStoreSlot ^ AllocateNamedDataSlot(System::String ^ name);
public static LocalDataStoreSlot AllocateNamedDataSlot (string name);
static member AllocateNamedDataSlot : string -> LocalDataStoreSlot
Public Shared Function AllocateNamedDataSlot (name As String) As LocalDataStoreSlot

매개 변수

name
String

할당할 데이터 슬롯의 이름입니다.

반환

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

두 번째 예

다음 예제에서는 명명 된 데이터 슬롯을 사용 하 여 스레드별 정보를 저장 하는 방법을 보여 줍니다.

참고

메서드는 AllocateNamedDataSlot GetNamedDataSlot 아직 할당 되지 않은 경우 슬롯을 할당 하기 때문에 예제 코드는 메서드를 사용 하지 않습니다. 메서드를 사용 하는 경우 AllocateNamedDataSlot 프로그램 시작 시 주 스레드에서 호출 해야 합니다.

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 사용에 대한 자세한 내용은 스레드 로컬 스토리지: 스레드 상대 정적 필드 및 데이터 슬롯을 참조하세요.

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

메서드가 AllocateNamedDataSlot GetNamedDataSlot 아직 할당 되지 않은 경우 슬롯을 할당 하기 때문에 메서드를 사용 하 여 명명 된 데이터 슬롯을 할당할 필요가 없습니다.

참고

메서드를 사용 하는 경우 AllocateNamedDataSlot 지정 된 이름의 슬롯이 이미 할당 된 경우 예외를 throw 하기 때문에 프로그램 시작 시 주 스레드에서 호출 해야 합니다. 슬롯이 이미 할당 되었는지 여부를 테스트할 수 있는 방법은 없습니다.

이 메서드를 사용 하 여 할당 된 슬롯은로 해제 해야 합니다 FreeNamedDataSlot .

적용 대상

추가 정보