ThreadStaticAttribute クラス

定義

静的フィールドの値がスレッドごとに一意であることを示します。

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
継承
ThreadStaticAttribute
属性

次のコード例は、 ThreadStaticAttribute を使用して、静的フィールドが各スレッドに対して一意であることを確認する方法を示しています。 このコードでは、各スレッドがスレッド静的フィールドに異なる要求 ID を割り当て、複数のメソッド呼び出しで要求処理をシミュレートします。

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

注釈

ThreadStaticAttributeでマークされたstatic フィールドはスレッド間で共有されません。 実行中の各スレッドにはフィールドの個別のインスタンスがあり、そのフィールドの値を個別に設定して取得します。 フィールドが別のスレッドでアクセスされる場合は、別の値が含まれます。

ThreadStaticAttribute 属性をフィールドに適用するだけでなく、static (C# または F#) または Shared (Visual Basic) として定義する必要もあります。

ThreadStaticAttributeでマークされたフィールドの初期値は指定しないでください。 このような初期化は、クラス コンストラクターが実行されるときに 1 回だけ発生するため、1 つのスレッドにのみ影響します。 初期値を指定しない場合、フィールドは値型の場合は既定値に初期化され、参照型の場合は null されます。

この属性をそのまま使用し、そこから派生させないでください。

属性の使用の詳細については、「 属性」を参照してください。

コンストラクター

名前 説明
ThreadStaticAttribute()

ThreadStaticAttribute クラスの新しいインスタンスを初期化します。

プロパティ

名前 説明
TypeId

派生クラスで実装されている場合は、この Attributeの一意の識別子を取得します。

(継承元 Attribute)

メソッド

名前 説明
Equals(Object)

このインスタンスが指定したオブジェクトと等しいかどうかを示す値を返します。

(継承元 Attribute)
GetHashCode()

このインスタンスのハッシュ コードを返します。

(継承元 Attribute)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
IsDefaultAttribute()

派生クラスでオーバーライドされた場合、このインスタンスの値が派生クラスの既定値であるかどうかを示します。

(継承元 Attribute)
Match(Object)

派生クラスでオーバーライドされた場合、このインスタンスが指定したオブジェクトと等しいかどうかを示す値を返します。

(継承元 Attribute)
MemberwiseClone()

現在の Objectの簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

明示的なインターフェイスの実装

名前 説明
_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

一連の名前を対応する一連のディスパッチ識別子に割り当てます。

(継承元 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

インターフェイスの型情報を取得するために使用できるオブジェクトの型情報を取得します。

(継承元 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

オブジェクトが提供する型情報インターフェイスの数 (0 または 1) を取得します。

(継承元 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

オブジェクトによって公開されるプロパティとメソッドへのアクセスを提供します。

(継承元 Attribute)

適用対象

こちらもご覧ください