ThreadStaticAttribute Classe
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Indica che il valore di un campo statico è univoco per ogni 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
- Ereditarietà
- Attributi
Esempio
Il codice di esempio seguente illustra come usare per ThreadStaticAttribute assicurarsi che un campo statico sia univoco per ogni thread. Nel codice ogni thread assegna un ID richiesta diverso al campo thread-static e quindi simula l'elaborazione delle richieste tra più chiamate al metodo.
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
Commenti
Un static campo contrassegnato con ThreadStaticAttribute non è condiviso tra thread. Ogni thread in esecuzione ha un'istanza separata del campo e imposta in modo indipendente e ottiene i valori per tale campo. Se si accede al campo in un thread diverso, conterrà un valore diverso.
Oltre ad applicare l'attributo ThreadStaticAttribute a un campo, è necessario definirlo anche come static (in C# o F#) o Shared (in Visual Basic).
Note
Non specificare i valori iniziali per i campi contrassegnati con ThreadStaticAttribute. Tale inizializzazione si verifica una sola volta, quando viene eseguito il costruttore della classe e pertanto influisce su un solo thread. Se non si specifica un valore iniziale, il campo verrà inizializzato sul valore predefinito se si tratta di un tipo valore o se null si tratta di un tipo riferimento.
Usare questo attributo così come è e non derivare da esso.
Per altre informazioni sull'uso degli attributi, vedere Attributi.
Costruttori
| Nome | Descrizione |
|---|---|
| ThreadStaticAttribute() |
Inizializza una nuova istanza della classe ThreadStaticAttribute. |
Proprietà
| Nome | Descrizione |
|---|---|
| TypeId |
Se implementato in una classe derivata, ottiene un identificatore univoco per questo Attribute. (Ereditato da Attribute) |
Metodi
| Nome | Descrizione |
|---|---|
| Equals(Object) |
Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato. (Ereditato da Attribute) |
| GetHashCode() |
Restituisce il codice hash per questa istanza. (Ereditato da Attribute) |
| GetType() |
Ottiene il Type dell'istanza corrente. (Ereditato da Object) |
| IsDefaultAttribute() |
Quando sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito per la classe derivata. (Ereditato da Attribute) |
| Match(Object) |
Quando sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza è uguale a un oggetto specificato. (Ereditato da Attribute) |
| MemberwiseClone() |
Crea una copia superficiale del Objectcorrente. (Ereditato da Object) |
| ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object) |
Implementazioni dell'interfaccia esplicita
| Nome | Descrizione |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Esegue il mapping di un set di nomi a un set corrispondente di identificatori dispatch. (Ereditato da Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Recupera le informazioni sul tipo per un oggetto, che può essere utilizzato per ottenere le informazioni sul tipo per un'interfaccia. (Ereditato da Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Recupera il numero di interfacce di informazioni sul tipo fornite da un oggetto (0 o 1). (Ereditato da Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Fornisce l'accesso alle proprietà e ai metodi esposti da un oggetto . (Ereditato da Attribute) |
Si applica a
Vedi anche
- Attribute
- Thread
- AsyncLocal<T>
- l'estensione dei metadati tramite attributi
- di threading gestito