I just answered a question at SO about lazy loading which involved the double check pattern. It’s a really useful pattern for lazy loading since it hurt performance a lot less than always locking.
I thought that I should share and explain why by using some comments:
public sealed class Lazy<T> where T : class
{
private readonly object _syncRoot = new object();
private readonly Func<T> _factory;
private T _value;
public Lazy(Func<T> factory)
{
if (factory == null) throw new ArgumentNullException("factory");
_factory = factory;
}
public T Value
{
get
{
if (_value == null)
{
lock (_syncRoot)
{
if (_value == null)
{
_value = _factory();
}
}
}
return _value;
}
}
public override string ToString()
{
return _value == null ? "Not created" : _value.ToString();
}
}
The double check pattern allows us to have lock free code (other than when the instance is created) which is a huge performance gain compared to using a single lock.
Feel free to use the code in .NET versions earlier than 4.