Thread.GetNamedDataSlot(String) Метод

Определение

Ищет именованную область данных. Для улучшения производительности используйте поля, отмеченные атрибутом ThreadStaticAttribute.

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

Параметры

name
String

Имя локальной области данных.

Возвращаемое значение

LocalDataStoreSlot

Объект 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

Второй пример

В следующем примере показано, как использовать именованную область данных для хранения сведений о конкретном потоке.

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 см. в разделе Local служба хранилища потока: Thread-Relative статических полей и слотов данных.

Потоки используют механизм локальной памяти хранилища для хранения данных конкретного потока. Среда CLR выделяет массив хранилища данных с несколькими слотами каждому процессу при его создании. Поток может выделить область данных в хранилище данных, сохранить и извлечь значение данных в слоте и освободить слот для повторного использования после истечения срока действия потока. Области данных являются уникальными для каждого потока. Ни один другой поток (даже не дочерний поток) не может получить эти данные.

Если именованный слот не существует, выделяется новый слот. Именованные слоты данных являются общедоступными и могут управляться любым пользователем.

Применяется к

См. также раздел