默认情况下,静态字段在同一个应用程序域中访问这些字段的所有线程间共享。但是使用ThreadStaticAttribute将任意static字段标记为线程间不可共享的。
//例如下面代码:
pubic class Foo { [ThreadStaticAttribute()] public static string bar="Initialized string"; }
下面不妨做个测试:
首先写个常规的static字段使用方法:
public class ThreadStaticField { //定义静态变量bar public static string bar = "Initialized String"; //显示静态变量值方法 public static void DisplayStaticFieldValue() { string msg = $"测试1:{Thread.CurrentThread.GetHashCode()}" + $" 包含静态变量的值为:{bar}"; Console.WriteLine(msg); } }
那么第二种是使用了ThreadStaticAttribute的静态字段的方法:
public class ThreadStaticField { //定义静态变量bar [ThreadStaticAttribute] public static string bar = "Initialized String"; //显示静态变量值方法 public static void DisplayStaticFieldValue() { string msg = $"测试2:{Thread.CurrentThread.GetHashCode()}" + $" 包含静态变量的值为:{bar}"; Console.WriteLine(msg); } }
调用方法为:
public static void Test() { ThreadStaticField.DisplayStaticFieldValue(); Thread newStaticFieldThread = new Thread(ThreadStaticField.DisplayStaticFieldValue); newStaticFieldThread.Start(); ThreadStaticField.DisplayStaticFieldValue(); }
执行程序结果为:
分析:很明显可以看到,测试1的当前线程的散列值为9,而新线程的散列值为10,其余都相同。
测试2中bar字段仅在访问它的第一个线程中被初始化,在所有其他线程中,这个字段被初始化为null,因此要记住:在任何线程中使用标记为ThreadStaticAttribute的静态字段之前,都要进行初始化,否则仅有当前的一个线程得到该初始值。