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

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

关键点:

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

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

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

示例:

cs 复制代码
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}");
    }
}

输出:

cs 复制代码
线程 ID: 2, 值: 20
线程 ID: 1, 值: 10

解释:

主线程将 _threadLocalValue 设置为 10。

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

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

使用场景:

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

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

局限性:

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

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

替代方案:

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

使用 ThreadLocal<T> 的示例:

cs 复制代码
using System;
using System.Threading;

class Program
{
    private static ThreadLocal<int> _threadLocalValue = new ThreadLocal<int>(() => 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}");
    }
}

输出:

cs 复制代码
线程 ID: 2, 值: 20
线程 ID: 1, 值: 10

总结:

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

相关推荐
葬歌倾城12 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue14 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王14 小时前
hello判断
开发语言·c#
金增辉16 小时前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future141218 小时前
C#学习日记
开发语言·学习·c#
傻啦嘿哟19 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
唐青枫1 天前
C#.NET log4net 详解
c#·.net
Nemo_XP1 天前
HttpHelper类处理两种HTTP POST请求
c#
lijingguang1 天前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented2 天前
【C#中路径相关的概念】
开发语言·c#