/ Published in: C#
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 l = new LazyLoader(() => 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();
Usage:
LazyLoader l = new LazyLoader(() => 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();
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <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 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) { } _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(); } } } }