[ThreadStatic]
是 C# 中的一个特性(Attribute),用于指示静态字段的值在每个线程中是唯一的。这意味着每个访问该字段的线程都有自己独立的副本,从而避免了线程之间的干扰。
关键点:
-
线程特定存储:每个线程都有自己独立的
[ThreadStatic]
字段实例。 -
静态字段要求:该特性只能应用于静态字段。
-
初始化:在每个线程中,字段会被初始化为默认值(如
null
、0
、false
),除非显式设置。
示例:
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();