Found a couple good blogs abouot Lazy<T> in the new .Net 4.0 framework.
http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/
http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx
The key points are:
- When you create a new object, you no longer do "MyClass = new MyClass();". Instead, you do "Lazy<MyClass> = new Lazy<MyClass>();".
- For classes with no parameterless constructor, you need to do below
new Lazy<Pet>(delegate() { return new Pet("DuDu", "Siberian Husky"); });
- The Lazy<T> will NOT instantiate the instance until its value is accessed.
- Its default mode is NOT thread safe.
However, you can make it threadsafe by doing below constructors:
1) public Lazy(LazyExecutionMode mode)
2) public Lazy(Func<T> valueFactory,LazyExecutionMode mode)
What is the big gain here? Well, you no longer need to write your own code to implement the laziness as you did in .Net 3.5, or earlier. Instead, the constructor helps you to implement the lazy loading.
Is it cool to be lazier but get the same thing done.
No comments:
Post a Comment