Thread.GetNamedDataSlot(String) Metoda

Definice

Vyhledá pojmenovaný datový slot. Pro lepší výkon místo toho použijte pole označená ThreadStaticAttribute atributem .

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

Parametry

name
String

Název místního slotu dat.

Návraty

LocalDataStoreSlot

Přidělené LocalDataStoreSlot pro toto vlákno.

Příklady

Tato část obsahuje dva příklady kódu. První příklad ukazuje, jak použít pole, které je označeno atributem pro ThreadStaticAttribute uchování informací specifických pro vlákno. Druhý příklad ukazuje, jak stejnou věc provést pomocí slotu dat.

První příklad

Následující příklad ukazuje, jak použít pole, které je označeno pomocí k ThreadStaticAttribute blokování informací specifických pro vlákno. Tato technika poskytuje lepší výkon než technika, která je znázorněna v druhém příkladu.

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

Druhý příklad

Následující příklad ukazuje použití pojmenovaného datového slotu k ukládání informací specifických pro vlákno.

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

Poznámky

Důležité

.NET Framework poskytuje dva mechanismy pro použití místního úložiště vláken (TLS): statická pole relativní vzhledem k vláknům (to znamená pole označená atributem) a ThreadStaticAttribute datové sloty. Statická pole relativní vzhledem k vláknům poskytují mnohem lepší výkon než datové sloty a umožňují kontrolu typu v době kompilace. Další informace o používání protokolu TLS najdete v tématu Místní vlákno Storage: Thread-Relative statická pole a datové sloty.

Vlákna používají k ukládání dat specifických pro vlákno mechanismus paměti místního úložiště. Modul CLR (Common Language Runtime) přidělí každému procesu při vytvoření pole úložiště dat s více sloty. Vlákno může přidělit datový slot v datovém úložiště, uložit a načíst hodnotu dat v slotu a po vypršení platnosti vlákna slot znovu použít. Datové sloty jsou pro jedno vlákno jedinečné. Žádná jiná vlákna (ani podřízené vlákno) tato data nemůže získat.

Pokud pojmenovaný slot neexistuje, je přidělen nový slot. Pojmenované datové sloty jsou veřejné a může s nimi manipulovat kdokoli.

Platí pro

Viz také