c#之ThreadStatic特性

一、ThreadStaticAttribute

指示静态字段的值对于每个线程都是唯一的。用 ThreadStaticAttribute 标记的 static 字段不在线程之间共享。每个执行线程都有单独的字段实例,并且独立地设置及获取该字段的值。如果在不同的线程中访问该字段,则该字段将包含不同的值

二、代码示例

 先来看看不标记特性:

 private static Dictionary<string, string> dic = new Dictionary<string, string>();
        static void Main(string[] args)
        {
            Task task1 = new Task(() =>
              {
                  if (dic == null)
                      dic = new Dictionary<string, string>();
                  dic.Add("11", "22");
                  dic.Add("22", "33");
                  dic.Add("33", "44");
                  Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
                  Console.WriteLine(dic.Count);
              });
            Task task2 = new Task(() =>
            {
                if (dic == null)
                    dic = new Dictionary<string, string>();
                dic.Add("44", "55");
                dic.Add("55", "66");
                Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine(dic.Count);
            });
            task1.Start();
            task2.Start();
            Console.ReadKey();
        }

输出结果:

 

挂上特性ThreadStatic:

 [ThreadStatic]
        private static Dictionary<string, string> dic = new Dictionary<string, string>();
        static void Main(string[] args)
        {
            Task task1 = new Task(() =>
              {
                  if (dic == null)
                      dic = new Dictionary<string, string>();
                  dic.Add("11", "22");
                  dic.Add("22", "33");
                  dic.Add("33", "44");
                  Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
                  Console.WriteLine(dic.Count);
              });
            Task task2 = new Task(() =>
            {
                if (dic == null)
                    dic = new Dictionary<string, string>();
                dic.Add("44", "55");
                dic.Add("55", "66");
                Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
                Console.WriteLine(dic.Count);
            });
            task1.Start();
            task2.Start();
            Console.ReadKey();
        }

输出结果:

 

可以看到使用特性ThreadStatic,在每个线程中变量dic,都是独立存在的,就好比class的每个实例都有其独立的成员(字段、属性、函数)。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值