Return to Snippet

Revision: 49571
at July 25, 2011 15:28 by stewartrae


Initial Code
/// <summary>
    /// A lazy loader - loads an object into the instance variable on demand.
    /// Always returns the same instance once loaded.
    /// Thread safe.
    /// </summary>
    /// <typeparam name="T">The instance type</typeparam>
    public class LazyLoader<T> where T : class
    {
        private static object _padlock = new object();
        private T _instance;
        private Func<T> _loader;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="loader">The function to load/instantiate the instance</param>
        public LazyLoader(Func<T> loader)
        {
            if (loader == null)
            {
                throw new ArgumentNullException("loader");
            }
            _loader = loader;
        }

        /// <summary>
        /// Returns the loaded instance.
        /// </summary>
        public T Instance
        {
            get
            {
                EnsureLoad();
                return _instance;
            }
        }

        /// <summary>
        /// Ensures that the instance is loaded.
        /// </summary>
        public void EnsureLoad()
        {
            // Use double-checked locking pattern when lazy-loading the data.
            if (_instance == null)
            {
                lock (_padlock)
                {
                    if (_instance == null)
                    {
                        _instance = _loader();
                    }
                }
            }
        }

Initial URL

                                

Initial Description
A simple, thread-safe wrapper class for lazy-loading data into an instance on-demand (i.e. when the instance is first accessed.)

Usage:

LazyLoader<Foo> l = new LazyLoader<Foo>(() => Foo.LoadFromDataSource("DB Connection String"));

// For access to the lazy-loaded instance:
var x = l.Instance.Bar;

// Need to ensure that the data is loaded deterministically? Use this:
l.EnsureLoad();

Initial Title
LazyLoader - a simple, thread-safe class that can be used to load data on demand.

Initial Tags
load

Initial Language
C#