On a large enterprise applicaiton I work on we are currently unable to upgrade from .NET3.5 to .NET4.0, although there is plenty of situations where we could use the .Lazy<T> class. So in order to get us through until we upgrade to .NET I have implemented a very basic .NET 3.5 version which can easily be replaced with the Microsoft version at a later date.
/// <summary>
/// A pre-.NET4 Lazy<T> implementation
/// </summary>
public class LazyLoader<T>
where T : class
{
private readonly object padlock;
private readonly Func<T> function;
private bool hasRun;
private T instance;
public LazyLoader(Func<T> function)
{
this.hasRun = false;
this.padlock = new object();
this.function = function;
}
public T Value()
{
lock (padlock)
{
if (!hasRun)
{
instance = function.Invoke();
hasRun = true;
}
}
return instance;
}
}
No comments:
Post a Comment