一、ThreadStaticAttribute
指示静态字段的值对于每个线程都是唯一的。用 ThreadStaticAttribute 标记的 static 字段不在线程之间共享。每个执行线程都有单独的字段实例,并且独立地设置及获取该字段的值。如果在不同的线程中访问该字段,则该字段将包含不同的值
二、代码示例
先来看看不标记特性:
private static Dictionary<string, string> dic = new Dictionary<string, string>();
static void Main(string[] args)
{
Task task1 = new Task(() =>
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add("11", "22");
dic.Add("22", "33");
dic.Add("33", "44");
Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(dic.Count);
});
Task task2 = new Task(() =>
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add("44", "55");
dic.Add("55", "66");
Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(dic.Count);
});
task1.Start();
task2.Start();
Console.ReadKey();
}
输出结果:
挂上特性ThreadStatic:
[ThreadStatic]
private static Dictionary<string, string> dic = new Dictionary<string, string>();
static void Main(string[] args)
{
Task task1 = new Task(() =>
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add("11", "22");
dic.Add("22", "33");
dic.Add("33", "44");
Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(dic.Count);
});
Task task2 = new Task(() =>
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add("44", "55");
dic.Add("55", "66");
Console.WriteLine("线程ID:" + Thread.CurrentThread.ManagedThreadId);
Console.WriteLine(dic.Count);
});
task1.Start();
task2.Start();
Console.ReadKey();
}
输出结果:
可以看到使用特性ThreadStatic,在每个线程中变量dic,都是独立存在的,就好比class的每个实例都有其独立的成员(字段、属性、函数)。