Thread.SetData(LocalDataStoreSlot, Object) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Define os dados no slot especificado na thread em curso, para o domínio atual dessa thread. Para melhor desempenho, use campos marcados com o ThreadStaticAttribute atributo em vez disso.
public:
static void SetData(LocalDataStoreSlot ^ slot, System::Object ^ data);
public static void SetData(LocalDataStoreSlot slot, object data);
static member SetData : LocalDataStoreSlot * obj -> unit
Public Shared Sub SetData (slot As LocalDataStoreSlot, data As Object)
Parâmetros
- slot
- LocalDataStoreSlot
O LocalDataStoreSlot em que definir o valor.
- data
- Object
O valor a definir.
Exemplos
Esta seção contém dois exemplos de código. O primeiro exemplo mostra como usar um campo marcado com o ThreadStaticAttribute atributo para armazenar informação específica de cada thread. O segundo exemplo mostra como usar um slot de dados para fazer o mesmo.
Primeiro Exemplo
O exemplo seguinte mostra como usar um campo marcado com ThreadStaticAttribute para armazenar informação específica do thread. Esta técnica oferece melhor desempenho do que a técnica mostrada no segundo exemplo.
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
*/
open System
open System.Threading
type ThreadData() =
// Create a static variable to hold the data for each thread.
[<ThreadStatic; DefaultValue>]
static val mutable private threadSpecificData : int
static member ThreadStaticDemo() =
// Store the managed thread id for each thread in the static
// variable.
ThreadData.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.
printfn $"Data for managed thread {Thread.CurrentThread.ManagedThreadId}: {ThreadData.threadSpecificData}"
for i = 0 to 2 do
let newThread = Thread 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
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
Segundo exemplo
O exemplo seguinte demonstra como usar um slot de dados nomeado para armazenar informação específica de um thread.
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);
}
}
}
open System
open System.Threading
module Slot =
let private randomGenerator = Random()
let slotTest () =
// Set random data in each thread's data slot.
let slotData = randomGenerator.Next(1, 200)
let threadId = Thread.CurrentThread.ManagedThreadId
Thread.SetData(Thread.GetNamedDataSlot "Random", slotData)
// Show what was saved in the thread's data slot.
printfn $"Data stored in thread_{threadId}'s data slot: {slotData, 3}"
// Allow other threads time to execute SetData to show
// that a thread's data slot is unique to itself.
Thread.Sleep 1000
let newSlotData = Thread.GetData(Thread.GetNamedDataSlot "Random") :?> int
if newSlotData = slotData then
printfn $"Data in thread_{threadId}'s data slot is still: {newSlotData, 3}"
else
printfn $"Data in thread_{threadId}'s data slot changed to: {newSlotData, 3}"
let newThreads =
[| for _ = 0 to 3 do
let thread = Thread Slot.slotTest
thread.Start()
thread |]
Thread.Sleep 2000
for tread in newThreads do
tread.Join()
printfn $"Thread_{tread.ManagedThreadId} finished."
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
Observações
Importante
.NET Framework fornece dois mecanismos para usar armazenamento local de threads (TLS): campos estáticos relativos a threads (ou seja, campos marcados com o atributo ThreadStaticAttribute) e slots de dados. Campos estáticos relativos a threads oferecem um desempenho muito melhor do que os slots de dados e permitem a verificação de tipos em tempo de compilação. Para mais informações sobre o uso do TLS, consulte Thread Local Storage: Thread-Relative Campos Estáticos e Espaços de Dados.
As threads utilizam um mecanismo local de armazenamento de memória para armazenar dados específicos de cada thread. O runtime da linguagem comum aloca um array de armazenamento de dados multi-slot a cada processo quando este é criado. A thread pode alocar um slot de dados no armazenamento de dados, armazenar e recuperar um valor de dados no slot, e libertar o slot para reutilização após o término do procedimento da thread e o Thread objeto ter sido recuperado por recolha de lixo. Os espaços de dados são únicos por thread. Nenhum outro thread (nem sequer um thread filho) consegue obter esses dados.
Note
SetData é um Shared método que se aplica sempre ao thread em execução, mesmo que o chame usando uma variável que se refira a outro thread. Para evitar confusão, use o nome da classe ao chamar Shared os métodos: Thread.SetData(testSlot, "test data").