ThreadStaticAttribute Klasa
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Wskazuje, że wartość pola statycznego jest unikatowa dla każdego wątku.
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
- Dziedziczenie
- Atrybuty
Przykłady
Poniższy przykładowy kod pokazuje, jak używać elementu , ThreadStaticAttribute aby upewnić się, że pole statyczne jest unikatowe dla każdego wątku. W kodzie każdy wątek przypisuje inny identyfikator żądania do pola statycznego wątku, a następnie symuluje przetwarzanie żądań w wielu wywołaniach metod.
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
Uwagi
static Pole oznaczone znakiem ThreadStaticAttribute nie jest współużytkowane między wątkami. Każdy wykonujący wątek ma oddzielne wystąpienie pola i niezależnie ustawia i pobiera wartości dla tego pola. Jeśli dostęp do pola jest uzyskiwany w innym wątku, będzie zawierać inną wartość.
Oprócz zastosowania atrybutu ThreadStaticAttribute do pola należy również zdefiniować go jako static (w języku C# lub F#) lub Shared (w Visual Basic).
Uwaga / Notatka
Nie należy określać początkowych wartości pól oznaczonych symbolem ThreadStaticAttribute. Taka inicjalizacja występuje tylko raz, gdy konstruktor klasy jest wykonywany, a zatem ma wpływ tylko na jeden wątek. Jeśli nie określisz wartości początkowej, pole zostanie zainicjowane do jego wartości domyślnej, jeśli jest to typ wartości lub null jeśli jest to typ odwołania.
Użyj tego atrybutu, tak jak jest, i nie pochodzi z niego.
Aby uzyskać więcej informacji na temat używania atrybutów, zobacz Atrybuty.
Konstruktory
| Nazwa | Opis |
|---|---|
| ThreadStaticAttribute() |
Inicjuje nowe wystąpienie klasy ThreadStaticAttribute. |
Właściwości
| Nazwa | Opis |
|---|---|
| TypeId |
Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attribute. (Odziedziczone po Attribute) |
Metody
| Nazwa | Opis |
|---|---|
| Equals(Object) |
Zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi. (Odziedziczone po Attribute) |
| GetHashCode() |
Zwraca kod skrótu dla tego wystąpienia. (Odziedziczone po Attribute) |
| GetType() |
Pobiera Type bieżącego wystąpienia. (Odziedziczone po Object) |
| IsDefaultAttribute() |
Po zastąpieniu w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną dla klasy pochodnej. (Odziedziczone po Attribute) |
| Match(Object) |
Po zastąpieniu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi. (Odziedziczone po Attribute) |
| MemberwiseClone() |
Tworzy płytkią kopię bieżącego Object. (Odziedziczone po Object) |
| ToString() |
Zwraca ciąg reprezentujący bieżący obiekt. (Odziedziczone po Object) |
Jawne implementacje interfejsu
| Nazwa | Opis |
|---|---|
| _Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) |
Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania. (Odziedziczone po Attribute) |
| _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
Pobiera informacje o typie obiektu, którego można użyć do uzyskania informacji o typie dla interfejsu. (Odziedziczone po Attribute) |
| _Attribute.GetTypeInfoCount(UInt32) |
Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1). (Odziedziczone po Attribute) |
| _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
Zapewnia dostęp do właściwości i metod uwidocznionych przez obiekt. (Odziedziczone po Attribute) |