用于实现线程隔离的线程本地变量。包含在托管线程对象Thread中。
对于同一个线程本地变量,各个线程分别有独立的值,修改的值只针对修改的线程可见。
示例:
public class demo7
{
[ThreadStatic]
static int a, b;
public static void test()
{
var thread1 = new Thread(Thread1);
var thread2 = new Thread(Thread2);
thread1.Start();
thread2.Start();
}
private static void Thread1()
{
a = 1;
b = 2;
Console.WriteLine("a = {0},from thead1",a);
Console.WriteLine("b = {0},from thead1", b);
}
private static void Thread2()
{
a = 10;
b = 20;
Console.WriteLine("a = {0},from thread2", a);
Console.WriteLine("b = {0},from thread2", b);
}
}
此时,当取消[ThreadStatic]特性时,输出