ThreadStaticAttribute Clase

Definición

Indica que el valor de un campo estático es único para cada subproceso.

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
Herencia
ThreadStaticAttribute
Atributos

Ejemplos

En el código de ejemplo siguiente se muestra cómo usar ThreadStaticAttribute para asegurarse de que un campo estático es único para cada subproceso. En el código, cada subproceso asigna un identificador de solicitud diferente al campo estático del subproceso y, a continuación, simula el procesamiento de solicitudes en varias llamadas 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

Comentarios

Un static campo marcado con ThreadStaticAttribute no se comparte entre subprocesos. Cada subproceso en ejecución tiene una instancia independiente del campo y establece y obtiene valores para ese campo de forma independiente. Si se accede al campo en un subproceso diferente, contendrá un valor diferente.

Además de aplicar el atributo ThreadStaticAttribute a un campo, también debe definirlo como static (en C# o F#) o Shared (en Visual Basic).

Note

No especifique valores iniciales para los campos marcados con ThreadStaticAttribute. Esta inicialización solo se produce una vez, cuando se ejecuta el constructor de clase y, por lo tanto, solo afecta a un subproceso. Si no especifica un valor inicial, el campo se inicializará en su valor predeterminado si es un tipo de valor o si null es un tipo de referencia.

Use este atributo tal como está y no derive de él.

Para obtener más información sobre el uso de atributos, vea Atributos.

Constructores

Nombre Description
ThreadStaticAttribute()

Inicializa una nueva instancia de la clase ThreadStaticAttribute.

Propiedades

Nombre Description
TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.

(Heredado de Attribute)

Métodos

Nombre Description
Equals(Object)

Devuelve un valor que indica si esta instancia es igual a un objeto especificado.

(Heredado de Attribute)
GetHashCode()

Devuelve el código hash de esta instancia.

(Heredado de Attribute)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsDefaultAttribute()

Cuando se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.

(Heredado de Attribute)
Match(Object)

Cuando se reemplaza en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

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

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

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

Recupera la información de tipo de un objeto, que se puede usar para obtener la información de tipo de una interfaz.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

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

Proporciona acceso a propiedades y métodos expuestos por un objeto .

(Heredado de Attribute)

Se aplica a

Consulte también