线程静态,是指静态成员在每一个线程内都有一份实例,而静态成员则是整个进程共享一份实例,所以,此注解千万不要跟线程池一同使用,因为你永远不能确定你现在新启动的进程有没有对线程静态变量进行过操作,永远无法确定它的值。
测试代码:
class ThreadStaticTest { [ThreadStatic] public static int iStatic = 0; public void F(object obj) { for (int i = 0; i < 1000; i++) { iStatic++; } Console.WriteLine(iStatic); Thread.Sleep(500); } }
测试:
ThreadStaticTest tst = new ThreadStaticTest(); for (int i = 0; i < 20; i++) { ThreadPool.QueueUserWorkItem(tst.F); Thread.Sleep(500); } Console.WriteLine(ThreadStaticTest.iStatic);
结果: