内容目录
[ThreadStatic]
private static bool HasCreated = false;
[ThreadStatic]
private static int Value = 0;
void Main()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
ThreadLocal<string> a = new ThreadLocal<string>(() =>
{
if (HasCreated) return Value.ToString();
else
{
Value = Thread.CurrentThread.ManagedThreadId;
HasCreated = true;
return Value.ToString();
}
});
new Thread(() =>
{
Console.WriteLine("代码1 线程id:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("代码1 值:" + a.Value);
Thread.Sleep(1000);
}).Start();
new Thread(() =>
{
Thread.Sleep(1000);
Console.WriteLine("代码2 线程id:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("代码2 值:" + a.Value);
}).Start();
Thread.Sleep(2000);
}
In the above code:
-
The variables
HasCreated
andValue
were originally instance-level fields decorated with[ThreadStatic]
, which caused the same values to be shared across different threads. -
After realizing this, changing these fields to be
static
allowed each thread to have its own separate instance of the variables, hence correctly allowing threads to maintain their values independently.
In summary, while using [ThreadStatic]
, it is important for the decorated fields to be static so that the values are unique to each thread and do not share state across different threads.
文章评论