Derik Whittaker

Syndication

News


Getting Lazy with System.Lazy

One of the pretty cool new nuggets inside the .Net 4.0 framework is System.Lazy and System.Lazy<T>.  What System.Lazy brings to the table is a way to create objects which may need to perform intensive operations and defer the execution of the operation until it is 100% absolutely needed.

Lets take a look at how to use the System.Lazy type.

To better convey how to use this type we should first create some context.  In our example (trivial i know) we will have an orders factory which creates orders.  Take a look at the code below.

Pay attention to the Console.WriteLine in each factory method, these lines will provide us an indication of when the execution of these methods takes place.

Now that we have context, lets look at the example code for System.Lazy

In the code below we are going to call into the order factory and NOT use the values it returns right away.

If we run this console application you will receive the following information:

image

You will notice that the second I call into the 2 methods they are executed, which is what is expected.  Now lets use the .Lazy namespace and see what changes

If we rerun this console application you will receive the following information:

image

Here you will notice that i have created my points to the methods, but they have not been executed.  I know this by taking a look at the .IsValueCreated property on the Lazy type.  Since this has returned False I know my pointers have not been executed.  However, the second we call .Value you will see the messages appear which tell us the pointers have been executed. 

Finally, if i recheck the .IsValueCreated property this time it returns True which tells me we have indeed executed our pointers.

As you can see using Lazy is easy and can be a very powerful tool in your tool chest.  But like everything else, this feature of the framework is NOT meant for ever scenario, use it where it makes sense.

Till next time,


Posted 05-19-2010 5:51 AM by Derik Whittaker
Filed under: ,

[Advertisement]

Comments

James Michael Hare wrote re: Getting Lazy with System.Lazy
on 05-19-2010 9:22 AM

Very nice.  It definitely beats writing your own lazy construction.

Steven Benner wrote re: Getting Lazy with System.Lazy
on 05-19-2010 2:57 PM

Cool! I don't need "lazy" execution very often, but this will be a nice time saver for the next time it comes up.

Thanks for the article.

CurtainDog wrote re: Getting Lazy with System.Lazy
on 05-20-2010 1:13 AM

Oh, can't the compiler do this kind of thing for me?

Asif wrote re: Getting Lazy with System.Lazy
on 05-20-2010 1:32 AM

nice one...

Mithun Ashok wrote re: Getting Lazy with System.Lazy
on 05-20-2010 1:51 AM

Nice,

u missed a constructor for order class

vv wrote re: Getting Lazy with System.Lazy
on 05-20-2010 3:54 AM

Liiitle correction not related to the topic with no offence.

Lambda

() => { return ordersFactory.FetchOrders(); }

can be just

() => ordersFactory.FetchOrders();

HisDivineShadow wrote re: Getting Lazy with System.Lazy
on 05-20-2010 4:15 AM

or indeed forget the lambda alltogether...

var ordersAsLazy = new Lazy<IList<Order>>(ordersFactory.FetchOrders);

...assuming the method signature of FetchOrders matches the delegate signature of the Lazy<> constructor.

From three levels of delegate indirection via two compiler-generated anonymous methods to one and nil?

Thomas Vanderhoof wrote re: Getting Lazy with System.Lazy
on 05-20-2010 8:29 AM

Thanks for the article. Will use that for my next lazy loading call when we move to 4.0.

Roku wrote re: Getting Lazy with System.Lazy
on 05-20-2010 8:33 AM

Stream Netflix and Hulu to your TV...  $49.95

Junior wrote re: Getting Lazy with System.Lazy
on 05-20-2010 11:54 AM

Hey thanks for the article, your example makes a lot of sense and was easy to understand.

Enam Enon wrote re: Getting Lazy with System.Lazy
on 05-20-2010 1:26 PM

Nice example, but I almost puked because of the name of your object that fetches the data. Factory creates it does not fetch anything.  Get your terms in order.

Derik Whittaker wrote re: Getting Lazy with System.Lazy
on 05-20-2010 1:32 PM

@Enam,

If the names of my 'SAMPLE' objects get in the way of ur learning, I am sorry, but that is your issue not mine.

David Sherwood wrote re: Getting Lazy with System.Lazy
on 05-20-2010 2:35 PM

How does this differ from having a property List<Orders> and then the FetchOrder function does not return anything but populates the list?

Muhammad Aslam wrote re: Getting Lazy with System.Lazy
on 05-20-2010 3:06 PM

I don't think that this new features will be popular too much - The reason is that the lazy people will not use it because they are lazy and active people will not use it because they don't want to be lazy :)

Behrooz wrote re: Getting Lazy with System.Lazy
on 05-21-2010 5:10 AM

@Muhammad Aslam:Agreed.

Usman Masood wrote re: Getting Lazy with System.Lazy
on 05-21-2010 6:44 AM

@David i agree with your point.... what extra edge does it provide.......

Edgar Estrada wrote re: Getting Lazy with System.Lazy
on 05-21-2010 12:28 PM

Despite all the crap some of the people are throwing at you, I want to thank you for your time and effort to write this article, and share it with all of us. You are the kind of people who make a change; don´t stop.

"The dogs bark because we gallop" --Cervantes

Regards.

DotNetShoutout wrote Getting Lazy with System.Lazy - Derik Whittaker - Devlicio.us - Just the Tasty Bits
on 05-23-2010 12:54 AM

Thank you for submitting this cool story - Trackback from DotNetShoutout

Chris Fulstow wrote re: Getting Lazy with System.Lazy
on 05-25-2010 11:15 PM

Great example, thanks Derik.

(As I understand it, a factory just hides away the details of how an object is created, it doesn't really matter if it also loads the object with data.)

Robert The Grey wrote re: Getting Lazy with System.Lazy
on 05-26-2010 5:54 PM

Hey Derik,

Great post - I like little nuggets like this that show off new framework features. It really gives us perspective when evaluating whether or not something should be used. You're quite right that this is not another hammer to be running around with, but I have to ask the following in relation to this:

Am I correct in assuming that all this behaviour is synchronous in nature? If so, then deferring execution to "when you really need it" isn't going to buy you any time.

For this particular example, wouldn't you be better off plugging in Reactive Extensions, taking advantage of the push features of IObservable, thereby bringing it into an asynchronous paradigm which means you don't have to worry about the messy implementation detail of "waiting until the last minute".

To my mind, that's a much better way of Processing Orders (i.e. a Domain concern), but I can see the System.Lazy coming in handy for plumbing code deep in your architecture, but I don't think it has any place in your Domain when you have powerful tools like Rx at your disposal. I think that using System.Lazy in your Domain business logic isn't going to do you any favours, and I think a new breed of subtle bugs will emerge before long. You just have to look at deferred execution for LINQ and how long people took to wrap their heads around it. System.Lazy is more explicit about the intention yes, but I think the same bugs will show their faces...

Just my thoughts...

All the best,

Robert The Grey

Phydelta wrote Links Interesantes de .NET en general
on 09-27-2010 5:21 PM

Links Interesantes de .NET en general

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)