LazyInitializer.EnsureInitialized是frameworks4.0引入的新东西,实现对属性延时初始化的功能,它作用在System.Threading命名空间下,所以,它与多线程有着密切的关系,即当多人同步使用这个方法时,对存储的对象有着某种作用,这是msdn的相关说明:
这个方法可以用于多个执行者初始化Target目录对象。
在多个执行者同时存取这个方法的情况下,可能会建立多个T执行个体,但只有一个执行个体会存储至target。在些类情况下,这个方法将不会放置未储存的对象。如果这类对象必须被放置,则由呼叫端判断未使的对象,然后再对物件进行适当的放置。
对于概念不清楚的同步,没有关系,看下面的例子如完全明白了,呵呵
下面的实例介绍了对属性的两个初始化,并进行比较,延时初始化的好处,即在对象使用时再去初始化它,当一个方法体中,如果一个对象初始化了一次,不要再进行重复的初始化工作。
代码1,展现了性能不好的情况
代码2,展现了优化的情况
代码3,微软为了我们进行了封装,在多线程中表现更好
代码1:
class TestLazyInitializer1 { public People People { get { return new People(); } } public void Print1() { Console.WriteLine(People.Name); } public void Print2() { Console.WriteLine(People.Name); } }
代码2:
class TestLazyInitializer2 { People _people; public People People { get { return _people == null ? (_people = new People()) : _people; } } public void Print1() { Console.WriteLine(People.Name); } public void Print2() { Console.WriteLine(People.Name); } }
代码3:
class TestLazyInitializer { private People _people; /// <summary> /// 延时初始化指定属性 /// </summary> public People People { get { return LazyInitializer.EnsureInitialized( ref _people, () => { return new People(); }); } } public void Print1() { Console.WriteLine(People.Name); } public void Print2() { Console.WriteLine(People.Name); } }
而它们运行的结果,我们可想而知了,当一个类中多次使用同一个对象时,性能不好的,返回的Name(当前时间),肯定是不同的,而性能好的,只初始化一次的,返回的Name(当前时间)肯定是一个值,呵呵。
JSLaq0hGXIrO1eacnLpbSyc5HSkhYpLa2lKi2BKi1pFNLSrlWlpZ0S0hL7k57eJ6Ql1ZVlmSotadSklZGo0pJGhrR+aD9y9NiMnbtm797+QPOWRw5snHN4/fHW1h87Kup7Qv6qJYxeaQnLZQOqO0mlVen4SdhrJa0+4zaITaxacnrUVUtY+k/a2LnTtWoJi5SWOJQCE9IS+4O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