线程静态就是一个由System.ThreadStaticAttribute属性注释的普通的静态字段。它的存取是根据线程来指定内存位置的,所以它的存取速度较慢。如果一个程序中同时有多个线程同时访问这个字段,则每个线程访问的都是独立的threadvalue 。例如主线程设置它为”Master Thread”,线程1设置它为”Thread 0” ,然后线程2设置它为” Thread 1” ,主线程读取它的时候,得到的是” Master Thread”。主线程设置的值在每个线程中是完全隔离的。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- namespace ThreadStaticConsole
- {
- class Program
- {
- [ThreadStatic]
- static string data = "unset";
- static void Main(string[] args)
- {
- Console.WriteLine("[Master] before={0}", data);
- data = "Master Thread";
- Console.WriteLine("[Master] after={0}", data);
- Thread[] threads = new Thread[2];
- for (int i = 0; i < 2; i++)
- {
- threads[i] = new Thread(delegate(object j)
- {
- Console.WriteLine("[Thread{0} before={1}", j, data); data = "Thread" + j;
- Console.WriteLine("[Thread{0}] after={1}", j, data);
- });
- threads[i].Start(i);
- }
- Array.ForEach(threads, delegate(Thread th) { th.Join(); });
- Console.WriteLine("[Master] after loop={0}", data);
- Console.ReadLine();
- }
运行结果:
rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C02%5Cclip_filelist.xml">
[Master] before=unset
[Master] after=Master Thread
[Thread0 before=
[Thread0] after=Thread0
[Thread1 before=
[Thread1] after=Thread1
[Master] after loop=Master Thread
rel="File-List" href="file:///C:%5CDOCUME%7E1%5CADMINI%7E1%5CLOCALS%7E1%5CTemp%5Cmsohtml1%5C03%5Cclip_filelist.xml">
可以看清楚,在设置data前,每个线程看到的data值为null。该注意的是线程静态字段它只由类构造函数初始化一次,并且在只在第一次引用该字段的线程上,其他线程再访问这个字段时,为字段的类型的默认值(defalut(T))