Thread.AllocateDataSlot Metodo

Definizione

Alloca uno slot di dati senza nome su tutti i thread. Per ottenere prestazioni migliori, usare i campi contrassegnati con l'attributo ThreadStaticAttribute.

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

Restituisce

LocalDataStoreSlot

Slot di dati denominato allocato su tutti i thread.

Esempio

In questa sezione sono riportati due esempi di codice. Nel primo esempio viene illustrato come utilizzare un campo contrassegnato con ThreadStaticAttribute l'attributo per contenere informazioni specifiche del thread. Nel secondo esempio viene illustrato come usare uno slot di dati per eseguire la stessa operazione.

Primo esempio

Nell'esempio seguente viene illustrato come utilizzare un campo contrassegnato con per ThreadStaticAttribute contenere informazioni specifiche del thread. Questa tecnica offre prestazioni migliori rispetto alla tecnica illustrata nel secondo esempio.

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

Secondo esempio

Nell'esempio di codice seguente viene illustrato come usare uno slot di dati per archiviare informazioni specifiche del thread.

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());
    }
}
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

Commenti

Importante

Il .NET Framework fornisce due meccanismi per l'uso dell'archiviazione thread-local (TLS): i campi statici relativi al thread (ovvero i campi contrassegnati con l'attributo ) e gli ThreadStaticAttribute slot di dati. I campi statici relativi ai thread offrono prestazioni migliori rispetto agli slot di dati e consentono il controllo dei tipi in fase di compilazione. Per altre informazioni sull'uso di TLS, vedere Thread Local Archiviazione: Thread-Relative Static Fields and Data Slots (Thread locale: Thread-Relative statici e slot di dati).

Lo slot viene allocato in tutti i thread.

I thread usano un meccanismo di memoria dell'archivio locale per archiviare dati specifici del thread. Common Language Runtime alloca una matrice di archivi dati multi-slot a ogni processo al momento della creazione. Il thread può allocare uno slot di dati nell'archivio dati, archiviare e recuperare un valore di dati nello slot e liberare lo slot per il riutilizzo dopo la scadenza del thread. Gli slot di dati sono univoci per ogni thread. Nessun altro thread (nemmeno un thread figlio) può ottenere i dati.

Si applica a

Vedi anche