ThreadStaticAttribute和ThreadLocal<T>使用区别总结

本文对比了.NET中ThreadStaticAttribute和ThreadLocal<T>两种线程本地存储方式的区别,并通过示例代码展示了它们如何确保每个线程拥有独立的数据副本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ThreadStaticAttribute和ThreadLocal<T>都是提供线程本地存储,ThreadLocal<T>是.net4才提供的。

ThreadStaticAttribute只能标注静态字段,而ThreadLocal<T>可以对实例字段才有效。

如果不标注ThreadStaticAttribute,则多个线程共享一个变量,这样的话会引起冲突的。

 class Program
    {


         static void Main()


        {


            Console.WriteLine("use [ThreadStaticAttribute]");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData1.ThreadStaticDemo);


                newThread.Start();


            }


 
            Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute]");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData2.ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("not use static member, use instance member");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread((new ThreadData3()).ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData4.ThreadStaticDemo);


                newThread.Start();


            }


             Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute], use ThreadLocal<int>");


            for (int i = 0; i < 3; i++)


            {


                Thread newThread = new Thread(ThreadData5.ThreadStaticDemo);


                newThread.Start();


            }


            Thread.Sleep(500);


            Console.WriteLine("not use [ThreadStaticAttribute], use ThreadLocal<int>");


             ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>


            {


                return "Thread" + Thread.CurrentThread.ManagedThreadId;


            });


 
            // Action that prints out ThreadName for the current thread


            Action action = () =>


            {


                // If ThreadName.IsValueCreated is true, it means that we are not the


                // first action to run on this thread.


                bool repeat = ThreadName.IsValueCreated;


 
                Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : "");


            };


 
            // Launch eight of them.  On 4 cores or less, you should see some repeat ThreadNames


            Parallel.Invoke(action, action, action, action, action, action, action, action);


             // Dispose when you are done


            ThreadName.Dispose();


         }


     }


 
    class ThreadData1


    {


        static int threadSpecificData;


        public static void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


 
        }


    }


 
    class ThreadData2


    {


        [ThreadStaticAttribute]//¨¦°?º?¨£¤Attribute¡À¨®¡ä[ThreadStatic] ®?¤¡§¬?


        static int threadSpecificData;


        public static void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


 
        }


    }


 
    class ThreadData3 //使º1®?º¦Ì¤y¤?¤¡§°2¨¦°?º¦Ì?¦?º?¡ì?ê???线?¨¬Ì£¤¨¤使º1®?¡ÂÁ?Ì?À?¢?


    {


        int threadSpecificData;


 
        public void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData = Thread.CurrentThread.ManagedThreadId;


 
            // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData);


         }


    }


     class ThreadData4


    {


        [ThreadStaticAttribute]//¨¦°?º?¨£¤Attribute¡À¨®¡ä[ThreadStatic] ®?¤¡§¬?


        static test t = null;


        public static void ThreadStaticDemo()


        {


            t = new test();


 
            Thread.Sleep(100);


            // Display the static data.


            Console.WriteLine(t.testvalue);


 
        }


    }


     class test


    {


        public int testvalue = 0;


         public test()


        {


            testvalue++;


        }


    }


 
 
    class ThreadData5


    {


        static ThreadLocal<int> threadSpecificData = new ThreadLocal<int>();//only in .net framework 4.0. no need to use [ThreadStaticAttribute]


        static public void ThreadStaticDemo()


        {


            // Store the managed thread id for each thread in the static


            // variable.


            threadSpecificData.Value = Thread.CurrentThread.ManagedThreadId;


             // Allow other threads time to execute the same code, to show


            // that the static data is unique to each thread.


            Thread.Sleep(100);


 
            // Display the static data.


            Console.WriteLine("Data for managed thread {0}: {1}",


                Thread.CurrentThread.ManagedThreadId, threadSpecificData.Value);


         }


    }


 
 

 



















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/545801 ,如需转载请自行联系原作者


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值