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();        }

 


---------------------
作者:Shine-Zhong
来源:CNBLOGS
原文:https://www.cnblogs.com/zsx-blog/p/16035238.html
版权声明:本文为作者原创文章,转载请附上博文链接!
内容解析By:CSDN,CNBLOG博客文章一键转载插件
posted @ 2022-04-27 18:54  JackieZhengChina  阅读(63)  评论(0编辑  收藏  举报