C# 中的一个特性(Attribute)[ThreadStatic]

[ThreadStatic] 是 C# 中的一个特性(Attribute),用于指示静态字段的值在每个线程中是唯一的。这意味着每个访问该字段的线程都有自己独立的副本,从而避免了线程之间的干扰。

关键点:

  • 线程特定存储:每个线程都有自己独立的 [ThreadStatic] 字段实例。

  • 静态字段要求:该特性只能应用于静态字段。

  • 初始化:在每个线程中,字段会被初始化为默认值(如 null0false),除非显式设置。

示例:

using System;
using System.Threading;

class Program
{
    [ThreadStatic]
    private static int _threadLocalValue;

    static void Main()
    {
        _threadLocalValue = 10;

        Thread thread = new Thread(() =>
        {
            _threadLocalValue = 20;
            Console.WriteLine($"线程 ID: {Thread.CurrentThread.ManagedThreadId}, 值: {_threadLocalValue}");
        });

        thread.Start();
        thread.Join();

        Console.WriteLine($"线程 ID: {Thread.CurrentThread.ManagedThreadId}, 值: {_threadLocalValue}");
    }
}

输出:

线程 ID: 2, 值: 20
线程 ID: 1, 值: 10

解释:
主线程将 _threadLocalValue 设置为 10。

新线程将自己的 _threadLocalValue 副本设置为 20。

每个线程都维护自己的值,展示了线程隔离的特性。

使用场景:
线程特定数据:适用于存储不应在线程间共享的数据,例如用户会话或事务上下文。

性能优化:减少多线程应用中对锁或同步机制的需求。

局限性:
无继承性:子线程不会从父线程继承该字段的值。

复杂性:由于线程特定的行为,可能会增加调试和维护的复杂性。

替代方案:
ThreadLocal:提供类似功能,并支持更多特性,如延迟初始化和对非静态字段的更好支持。

使用 ThreadLocal 的示例:

using System;
using System.Threading;

class Program
{
    private static ThreadLocal _threadLocalValue = new ThreadLocal(() => 10);

    static void Main()
    {
        Thread thread = new Thread(() =>
        {
            _threadLocalValue.Value = 20;
            Console.WriteLine($"线程 ID: {Thread.CurrentThread.ManagedThreadId}, 值: {_threadLocalValue.Value}");
        });

        thread.Start();
        thread.Join();

        Console.WriteLine($"线程 ID: {Thread.CurrentThread.ManagedThreadId}, 值: {_threadLocalValue.Value}");
    }
}

输出:

线程 ID: 2, 值: 20
线程 ID: 1, 值: 10

总结:
[ThreadStatic] 是实现线程本地存储的一种简单方式,但在更复杂的场景中,ThreadLocal 通常是更好的选择。

你可能感兴趣的:(C#,c#)