Thread.AllocateNamedDataSlot(String) Thread.AllocateNamedDataSlot(String) Thread.AllocateNamedDataSlot(String) Thread.AllocateNamedDataSlot(String) Method

Definition

Reserviert einen benannten Datenslot für alle Threads.Allocates a named data slot on all threads. Eine höhere Leistung erzielen Sie, wenn Sie stattdessen Felder verwenden, die mit dem ThreadStaticAttribute-Attribut markiert sind.For better performance, use fields that are marked with the ThreadStaticAttribute attribute instead.

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

Parameter

name
String String String String

Der Name des zu reservierenden Datenslots.The name of the data slot to be allocated.

Gibt zurück

Der reservierte benannte Datenslot für alle Threads.The allocated named data slot on all threads.

Ausnahmen

Es ist bereits ein benannter Datenslot mit dem angegebenen Namen vorhanden.A named data slot with the specified name already exists.

Beispiele

Dieser Abschnitt enthält zwei Codebeispiele.This section contains two code examples. Im ersten Beispiel wird gezeigt, wie ein Feld verwendet wird, das mit dem ThreadStaticAttribute-Attribut markiert ist, um Thread spezifische Informationen zu speichern.The first example shows how to use a field that is marked with the ThreadStaticAttribute attribute to hold thread-specific information. Im zweiten Beispiel wird gezeigt, wie ein Daten Slot verwendet wird, um das gleiche zu tun.The second example shows how to use a data slot to do the same thing.

Erstes BeispielFirst Example

Im folgenden Beispiel wird gezeigt, wie Sie ein Feld, das mit ThreadStaticAttribute markiert ist, verwenden, um Thread spezifische Informationen zu speichern.The following example shows how to use a field that is marked with ThreadStaticAttribute to hold thread-specific information. Diese Technik bietet eine bessere Leistung als die im zweiten Beispiel gezeigte Technik.This technique provides better performance than the technique that is shown in the second example.

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

Zweites BeispielSecond Example

Im folgenden Beispiel wird veranschaulicht, wie ein benannter Datenslot verwendet wird, um Thread spezifische Informationen zu speichern.The following example demonstrates how to use a named data slot to store thread-specific information.

Hinweis

Der Beispielcode verwendet nicht die AllocateNamedDataSlot-Methode, da die GetNamedDataSlot-Methode den Slot zuordnet, wenn er noch nicht zugeordnet wurde.The example code does not use the AllocateNamedDataSlot method, because the GetNamedDataSlot method allocates the slot if it has not already been allocated. Wenn die AllocateNamedDataSlot-Methode verwendet wird, sollte Sie im Haupt Thread beim Programmstart aufgerufen werden.If the AllocateNamedDataSlot method is used, it should be called in the main thread at program startup.

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

Hinweise

Wichtig

Der .NET Framework stellt zwei Mechanismen für die Verwendung von lokalem Thread Speicher (TLS) bereit: Thread relative statische Felder (d. h. Felder, die mit dem Attribut "ThreadStaticAttribute" gekennzeichnet sind) und Daten Slots.The .NET Framework provides two mechanisms for using thread local storage (TLS): thread-relative static fields (that is, fields that are marked with the ThreadStaticAttribute attribute) and data slots. Thread relative statische Felder bieten eine viel bessere Leistung als Daten Slots und ermöglichen eine Typüberprüfung zur Kompilierzeit.Thread-relative static fields provide much better performance than data slots, and enable compile-time type checking. Weitere Informationen zur Verwendung von TLS finden Sie unter [Thread Local Storage: Thread relative statische Felder und Daten Slots @ no__t-0.For more information about using TLS, see Thread Local Storage: Thread-Relative Static Fields and Data Slots.

Threads verwenden einen lokalen Speichermechanismus zum Speichern Thread spezifischer Daten.Threads use a local store memory mechanism to store thread-specific data. Die Common Language Runtime ordnet jedem Prozess bei der Erstellung ein Datenspeicher Array mit mehreren Slots zu.The common language runtime allocates a multi-slot data store array to each process when it is created. Der Thread kann einen Datenslot im Datenspeicher zuordnen, einen Datenwert im Slot speichern und Abrufen und den Slot wieder verwenden, nachdem der Thread abläuft.The thread can allocate a data slot in the data store, store and retrieve a data value in the slot, and free the slot for reuse after the thread expires. Daten Slots sind pro Thread eindeutig.Data slots are unique per thread. Diese Daten können von keinem anderen Thread (nicht sogar von einem untergeordneten Thread) erhalten werden.No other thread (not even a child thread) can get that data.

Es ist nicht erforderlich, die AllocateNamedDataSlot-Methode zu verwenden, um einen benannten Datenslot zuzuordnen, da die GetNamedDataSlot-Methode den Slot zuordnet, wenn er noch nicht zugeordnet wurde.It is not necessary to use the AllocateNamedDataSlot method to allocate a named data slot, because the GetNamedDataSlot method allocates the slot if it has not already been allocated.

Hinweis

Wenn die AllocateNamedDataSlot-Methode verwendet wird, sollte Sie im Haupt Thread beim Programmstart aufgerufen werden, da Sie eine Ausnahme auslöst, wenn bereits ein Slot mit dem angegebenen Namen zugewiesen wurde.If the AllocateNamedDataSlot method is used, it should be called in the main thread at program startup, because it throws an exception if a slot with the specified name has already been allocated. Es gibt keine Möglichkeit, zu testen, ob ein Slot bereits zugeordnet wurde.There is no way to test whether a slot has already been allocated.

Mit dieser Methode zugeordnete Slots müssen mit FreeNamedDataSlot freigegeben werden.Slots allocated with this method must be freed with FreeNamedDataSlot.

Gilt für:

Siehe auch