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

前端 未结 3 1368
时光取名叫无心
时光取名叫无心 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 01:42

    ThreadStatic Initialize only on first thread, ThreadLocal Initialize for each thread. Below is the simple demonstration:

        public static ThreadLocal _threadlocal =
            new ThreadLocal(() =>
            {
                return Thread.CurrentThread.ManagedThreadId;
            });
    
        public static void Main()
        {
            new Thread(() =>
            {
                for (int x = 0; x < _threadlocal.Value; x++)
                {
                    Console.WriteLine("First Thread: {0}", x);
                }
            }).Start();
    
            new Thread(() =>
            {
                for (int x = 0; x < _threadlocal.Value; x++)
                {
                    Console.WriteLine("Second Thread: {0}", x);
                }
            }).Start();
    
            Console.ReadKey();
        }
    

    enter image description here

提交回复
热议问题