Common Misunderstandings in Using C# ThreadLocal

2022年8月4日 2703点热度 1人点赞 0条评论
内容目录
[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:

  1. The variables HasCreated and Value were originally instance-level fields decorated with [ThreadStatic], which caused the same values to be shared across different threads.

  2. 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.

痴者工良

高级程序员劝退师

文章评论