C# 线程数据槽,ThreadStatic,ThreadLocal

        public static void Main(string[] args)
        {
            //当前主线程命名槽位
            var slot = Thread.AllocateDataSlot();
            Thread.SetData(slot, "jack");

            var t = new Thread(() =>
            {
                //slot对其他线程是不可见的
                var obj = Thread.GetData(slot);
                Console.WriteLine($"工作线程:{obj}");//无法打印内容
            });
            t.Start();

            var obj2 = Thread.GetData(slot);
            Console.WriteLine($"主线程{obj2}");//打印jack
    
            Console.ReadKey();
        }

 类似上面的还有ThreadStatic

        //ThreadStatic 指示每个静态类型字段对于每一个线程都是唯一的
        [ThreadStatic]
        static string name = string.Empty;
        public static void Main(string[] args)
        {
            name = "jack";
            var t = new Thread(() =>
            {
                Console.WriteLine($"工作线程:{name}");//无法打印内容
            });
            t.Start();

            Console.WriteLine($"主线程{name}");//打印jack

            Console.ReadKey();
        }

 

ThreadLocal
        public static void Main(string[] args)
        {
            ThreadLocal<string> local = new ThreadLocal<string>();
            local.Value = "jack";
            var t = new Thread(() =>
            {
                Console.WriteLine($"工作线程:{local.Value}");//无法打印内容
            });
            t.Start();

            Console.WriteLine($"主线程{local.Value}");//打印jack

            Console.ReadKey();
        }

 

posted on 2022-03-21 16:21  Shine-Zhong  阅读(323)  评论(0编辑  收藏  举报

导航