ThreadStatic v.s. ThreadLocal: is generic better than attribute?

前端 未结 3 1369
时光取名叫无心
时光取名叫无心 2020-11-30 01:19

[ThreadStatic] is defined using attribute while ThreadLocal uses generic. Why different design solutions were chosen? What are the advan

3条回答
  •  猫巷女王i
    2020-11-30 01:34

    The main idea behind ThreadStatic is to maintain a separate copy of the variable for each thread.

    class Program
        {
            [ThreadStatic]
            static int value = 10;
    
            static void Main(string[] args)
            {
                value = 25;
    
                Task t1 = Task.Run(() =>
                {
                    value++;
                    Console.WriteLine("T1: " + value);
                });
                Task t2 = Task.Run(() =>
                {
                    value++;
                    Console.WriteLine("T2: " + value);
                });
                Task t3 = Task.Run(() =>
                {
                    value++;
                    Console.WriteLine("T3: " + value);
                });
    
                Console.WriteLine("Main Thread : " + value);
    
                Task.WaitAll(t1, t2, t3);
                Console.ReadKey();
            }
        }
    

    In the above snippet, we have a separate copy of value for each thread, including the main thread.

    So, a ThreadStatic variable will be initialized to its default value on other threads except the thread on which it is created.

    If we want to initialize the variable on each thread in our own way, use ThreadLocal.

提交回复
热议问题