Meeting the needs of your business from a distance

Lazy Loading in .NET 4.0: Lazy<T>

by mark shiffer 7. October 2009 15:48

Came across this article over on Bill’s blog. I’m reprinting it here for future reference once I get a chance to work with .NET 4.

I love it when I find those small new bits of functionality in the .NET framework. It’s all the big items that get all the love at conferences and in magazines.

Lazy<T> is one of those items.

Let’s imagine you’re writing an application and in some scenarios, but not others,  you need a particular object. Furthermore, suppose that object you need is very expensive to create and use. You don’t want to create it everytime your application runs. You only want to create it when you need it.

Sure, you could manage all that yourself, but Lazy<T> makes it easy.  You just create a lazy wrapper on the expensive object:

Lazy<ExpensiveResource> ownedResource = new Lazy<ExpensiveResource>();

You can simply reference ‘ownedResource.Value’ to get at the expensive object. The first time you access ownedResource.Value, the expensive resource will get allocated, but not before.

Lazy<T> also has a boolean propoerty, named IsValueCreated, that you can check to see if the value has been created. That would be useful when you need to store information from the expensive resource, but only if it’s been used.

Supporting Types without default constructors

Lazy<T> does not enforce the new() constraint. You can use Lazy<T> for types that must be instantiated using a different constructor, or even a factory method. A second constructor specifies a Func<T> that returns the new expensive resource:

Lazy<ExpensiveResource> ownedResource = new Lazy<ExpensiveResource>(
    () => new ExpensiveResource("filename.data"));

You can use this second constructor to better control what code creates the expensive resource. I’ve used a different constructor here, but you could use a factory method, an IOC container, or any method.

We’re living in a Multi Core World

There are two other constructors in Lazy<T>:

public Lazy(bool isThreadSafe);
public Lazy(Func<T> valueFactory, bool isThreadSafe);

These two constructors indicate that you are running in a multi-threaded envrionment, and the lazy construction of of the owned object must be synchronized. (After all, it’s an expensive resource. You don’t want two of them.)

It’s a simple type, but it’s one of those types you’ll find yourself reaching for over and over again.

I’m glad it’s been added.

Tags:

Research | Programming

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Copyright © 2001-2010 MS Consulting, Inc. All Rights Reserved.