ThreadStatic特性

  带有threadStaticAttribute标记的静态字段在线程之间不共享。每个执行线程都有一个单独的字段实例,并独立地设置和获取该字段的值。如果在不同的线程上访问该字段,则它将包含不同的值。除了将threadStaticAttribute属性应用于字段之外,还必须将其定义为静态字段(在C中)或共享字段(在Visual Basic中)。不要为标记为threadStaticAttribute的字段指定初始值,因为此类初始化仅在类构造函数执行时发生一次(静态构造函数),因此只影响一个线程。

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             TestStaticThread TestStaticThread1 = new TestStaticThread();
 6             TestStaticThread TestStaticThread2 = new TestStaticThread();
 7 
 8             //Thread1
 9             Thread thread1 = new Thread(TestStaticThread1.SetStatic);
10             thread1.Start();
11 
12             //Thread2
13             Thread thread2 = new Thread(TestStaticThread2.GetStatic);
14             thread2.Start();
15 
16             Console.Read();
17         }
18     }
19 
20     public class TestA
21     {
22         public Guid Guid { get; set; }
23     }
24 
25     public class TestStaticThread
26     {
27         //指示各线程的静态字段值是否唯一
28         //依赖当前线程,独立于其它线程
29         [ThreadStatic]
30         private static TestA A;
31 
32         static TestStaticThread()
33         {
34             A = new TestA();
35             A.Guid = Guid.NewGuid();
36             Console.WriteLine("Default:" + A.Guid);
37         }
38 
39         public TestStaticThread()
40         {
41             Console.WriteLine("Constructor:" + A.Guid);
42         }
43 
44         public void SetStatic(object o)
45         {
46             A = new TestA();
47             A.Guid = Guid.NewGuid();
48             Console.WriteLine("SetStatic:" + A.Guid);
49         }
50 
51         public void GetStatic(object o)
52         {
53             if (A != null)
54             {
55                 Console.WriteLine("GetStatic:" + A.Guid);
56             }
57             else
58             {
59                 Console.WriteLine("GetStatic:A Is Null.");
60             }
61         }
62     }

  注:该字段依赖当前线程,当线程池的线程被重用时,可能该字段又表现为“公用”的了。及时清空可以一定程度上解决该问题。

原文地址:https://www.cnblogs.com/xuejietong/p/10997385.html