Lazy Loading

Today, I'll discuss one simple class that comes bundled with .NET 4.0. It's one of those small features that don't get much attention, but that truly come in handy. In this case, I'm talking about System.Lazy<T>. It's a simple class that provides support for lazy loading, so we no longer need to do those small pieces of code we've been doing throughout the years, whenever we had to deal with resources whose creation revealed to be expensive.

It's a simple class with a simple purpose, therefore it has a very simple usage, which I'll show in the small snippet below.

The code above will produce the following output:
Before bird creation
Creating Bird
I am a Duck
Before eagle creation
Creating Eagle
I am a Eagle

Notice that the Bird class is only instantiated when "bird.Value" and "eagle.Value" are accessed.
In the example above, I've shown:
- the usage of Lazy<T> in a way that instantiation will be done through a call to the default constructor
- the usage of Lazy<T> with a delegate responsible for the creation itself. This delegate will of course only be called at instantiation time (when the Lazy<T> Value property is accessed)

There are also other Lazy<T> constructors that provide further options regarding thread safety, which I will not discuss here.

Sem comentários: