ThreadStaticAttribute Classe

Definição

Indica que o valor de um campo estático é exclusivo 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
ThreadStaticAttribute
Atributos

Exemplos

O código de exemplo a seguir demonstra como usar para ThreadStaticAttribute garantir que um campo estático seja exclusivo para cada thread. No código, cada thread atribui uma ID de solicitação diferente ao campo estático de thread e simula o processamento de solicitações em várias 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

Comentários

Um static campo marcado com ThreadStaticAttribute não é compartilhado entre threads. Cada thread em execução tem uma instância separada do campo e define e obtém valores de forma independente para esse campo. Se o campo for acessado em um thread diferente, ele conterá um valor diferente.

Além de aplicar o atributo ThreadStaticAttribute a um campo, você 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. Essa inicialização ocorre apenas uma vez, quando o construtor de classe é executado e, portanto, afeta apenas um thread. Se você não especificar um valor inicial, o campo será inicializado para seu valor padrão se for um tipo de valor ou se null for um tipo de referência.

Use esse atributo como ele é e não derive dele.

Para obter mais informações sobre como usar atributos, consulte Atributos.

Construtores

Nome Description
ThreadStaticAttribute()

Inicializa uma nova instância da classe ThreadStaticAttribute.

Propriedades

Nome Description
TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para esse Attribute.

(Herdado de Attribute)

Métodos

Nome Description
Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash dessa instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

Nome Description
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo de um objeto, que podem ser usadas para obter as informações de tipo de uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também