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


/ Published in: C#
Save to your folder(s)

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();


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// A lazy loader - loads an object into the instance variable on demand.
  3. /// Always returns the same instance once loaded.
  4. /// Thread safe.
  5. /// </summary>
  6. /// <typeparam name="T">The instance type</typeparam>
  7. public class LazyLoader<T> where T : class
  8. {
  9. private static object _padlock = new object();
  10. private T _instance;
  11. private Func<T> _loader;
  12.  
  13. /// <summary>
  14. /// Constructor.
  15. /// </summary>
  16. /// <param name="loader">The function to load/instantiate the instance</param>
  17. public LazyLoader(Func<T> loader)
  18. {
  19. if (loader == null)
  20. {
  21. throw new ArgumentNullException("loader");
  22. }
  23. _loader = loader;
  24. }
  25.  
  26. /// <summary>
  27. /// Returns the loaded instance.
  28. /// </summary>
  29. public T Instance
  30. {
  31. get
  32. {
  33. EnsureLoad();
  34. return _instance;
  35. }
  36. }
  37.  
  38. /// <summary>
  39. /// Ensures that the instance is loaded.
  40. /// </summary>
  41. public void EnsureLoad()
  42. {
  43. // Use double-checked locking pattern when lazy-loading the data.
  44. if (_instance == null)
  45. {
  46. lock (_padlock)
  47. {
  48. if (_instance == null)
  49. {
  50. _instance = _loader();
  51. }
  52. }
  53. }
  54. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.