.net 4.0新特性-延迟初始化:Lazy(转),ThreadLocal<T>
2010-06-09 22:59 Clingingboy 阅读(1298) 评论(1) 编辑 收藏 举报感谢作者
http://www.cnblogs.com/anytao/archive/2009/10/29/must_net_33.html
http://www.cnblogs.com/me-sa/archive/2010/05/25/lazy-initialization-fx4.html
.net也有ThreadLocal了
http://www.cnblogs.com/tmrcp/archive/2009/07/17/1525506.html
.net 4.0之前用ThreadStatic标签代替
http://msdn.microsoft.com/en-us/library/dd997286(v=VS.100).aspx
补充
1. ThreadStatic的使用情况
代码
public class Demo7
{
static int count=100000;
public Demo7()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Task1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Task2));
}
public void Task1(object obj)
{
for (int i = 0; i < 100000; i++)
{
count++;
}
Console.WriteLine(DateTime.Now);
Console.WriteLine("Task1 count {0}", count);
}
public void Task2(object obj)
{
for (int i = 0; i < 100000; i++)
{
count++;
}
Console.WriteLine("Task2 count {0}", count);
}
}
{
static int count=100000;
public Demo7()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Task1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Task2));
}
public void Task1(object obj)
{
for (int i = 0; i < 100000; i++)
{
count++;
}
Console.WriteLine(DateTime.Now);
Console.WriteLine("Task1 count {0}", count);
}
public void Task2(object obj)
{
for (int i = 0; i < 100000; i++)
{
count++;
}
Console.WriteLine("Task2 count {0}", count);
}
}
显示效果
显示为乱数,其实不准的
2.使用了 ThreadStatic以后的结果
即该变量已经成为线程的局部变量,初始化的值也重置了