ThreadStaticAttribute Classe
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.
Indica que o valor de um campo estático é único para cada thread.
public ref class ThreadStaticAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)]
public class ThreadStaticAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)]
[System.Serializable]
public class ThreadStaticAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)]
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ThreadStaticAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)>]
type ThreadStaticAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)>]
[<System.Serializable>]
type ThreadStaticAttribute = class
inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Field, Inherited=false)>]
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ThreadStaticAttribute = class
inherit Attribute
Public Class ThreadStaticAttribute
Inherits Attribute
- Herança
- Atributos
Exemplos
O código de exemplo seguinte demonstra como usar o ThreadStaticAttribute para garantir que um campo estático é único para cada thread. No código, cada thread atribui um ID de pedido diferente ao campo estático da thread e depois simula o processamento de pedidos através de múltiplas chamadas de método.
using System;
using System.Threading;
class Program
{
[ThreadStatic]
private static string? _requestId;
static void Main()
{
Thread thread1 = new(ProcessRequest);
Thread thread2 = new(ProcessRequest);
thread1.Start("REQ-001");
thread2.Start("REQ-002");
thread1.Join();
thread2.Join();
Console.WriteLine("Main thread execution completed.");
}
static void ProcessRequest(object? requestId)
{
// Assign the request ID to the thread-static field.
_requestId = requestId as string;
// Simulate request processing across multiple method calls.
PerformDatabaseOperation();
PerformLogging();
}
static void PerformDatabaseOperation()
{
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}");
}
static void PerformLogging()
{
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}");
}
}
open System
open System.Threading
type ThreadLocal() =
[<ThreadStatic; DefaultValue>]
static val mutable private requestId: string option
static member PerformLogging() =
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {ThreadLocal.requestId.Value}")
static member PerformDatabaseOperation() =
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {ThreadLocal.requestId.Value}")
static member ProcessRequest(reqId: obj) =
ThreadLocal.requestId <- Some(reqId :?> string)
ThreadLocal.PerformDatabaseOperation()
ThreadLocal.PerformLogging()
[<EntryPoint>]
let main _ =
let thread1 = Thread(ThreadStart(fun () -> ThreadLocal.ProcessRequest("REQ-001")))
let thread2 = Thread(ThreadStart(fun () -> ThreadLocal.ProcessRequest("REQ-002")))
thread1.Start()
thread2.Start()
thread1.Join()
thread2.Join()
Console.WriteLine("Main thread execution completed.")
0
Imports System
Imports System.Threading
Module Program
<ThreadStatic>
Private _requestId As String
Sub Main()
Dim thread1 As New Thread(AddressOf ProcessRequest)
Dim thread2 As New Thread(AddressOf ProcessRequest)
thread1.Start("REQ-001")
thread2.Start("REQ-002")
thread1.Join()
thread2.Join()
Console.WriteLine("Main thread execution completed.")
End Sub
Sub ProcessRequest(ByVal requestId As Object)
' Assign the request ID to the thread-static field
_requestId = requestId.ToString()
' Simulate request processing across multiple method calls
PerformDatabaseOperation()
PerformLogging()
End Sub
Sub PerformDatabaseOperation()
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Processing DB operation for request {_requestId}")
End Sub
Sub PerformLogging()
Console.WriteLine($"Thread {Environment.CurrentManagedThreadId}: Logging request {_requestId}")
End Sub
End Module
Observações
Um static campo marcado com ThreadStaticAttribute não é partilhado entre threads. Cada thread em execução tem uma instância separada do campo, e define e obtém valores para esse campo de forma independente. Se o campo for acedido numa thread diferente, conterá um valor diferente.
Para além de aplicar o atributo ThreadStaticAttribute a um corpo, também deve defini-lo como static (em C# ou F#) ou Shared (em Visual Basic).
Note
Não especifique valores iniciais para campos marcados com ThreadStaticAttribute. Tal inicialização ocorre apenas uma vez, quando o construtor de classe é executado, e por isso afeta apenas um fio. Se não especificares um valor inicial, o campo será inicializado para o seu valor padrão se for um tipo de valor, ou para null se for um tipo de referência.
Usa este atributo tal como está, e não derives dele.
Para mais informações sobre o uso de atributos, consulte Atributos.
Construtores
| Name | Description |
|---|---|
| ThreadStaticAttribute() |
Inicializa uma nova instância da ThreadStaticAttribute classe. |
Propriedades
| Name | Description |
|---|---|
| TypeId |
Quando implementado numa classe derivada, obtém um identificador único para esta Attribute. (Herdado de Attribute) |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| GetHashCode() |
Devolve o código de hash para esta instância. (Herdado de Attribute) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| IsDefaultAttribute() |
Quando sobrescrito numa classe derivada, indica se o valor desta instância é o valor padrão para a classe derivada. (Herdado de Attribute) |
| Match(Object) |
Quando sobrescrito numa classe derivada, devolve um valor que indica se esta instância é igual a um objeto especificado. (Herdado de Attribute) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de despacho. (Herdado de Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera a informação de tipo de um objeto, que pode ser usada para obter a informação de tipo para uma interface. (Herdado de Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera o número de interfaces de informações de tipo que um objeto fornece (0 ou 1). (Herdado de Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Proporciona acesso a propriedades e métodos expostos por um objeto. (Herdado de Attribute) |
Aplica-se a
Ver também
- Attribute
- Thread
- AsyncLocal<T>
- Extensão dos Metadados Usando Atributos
- de threading gerenciado