LazyHolder.cs 828 B

123456789101112131415161718192021222324252627282930313233343536
  1. using System;
  2. namespace VCommon
  3. {
  4. /// <summary>
  5. /// 惰性初始化包裹, 线程安全
  6. /// </summary>
  7. public class LazyHolder<T> where T : class
  8. {
  9. private readonly object _lock = new object();
  10. private readonly Func<T> _initFunc;
  11. private T _heldInstance;
  12. public LazyHolder(Func<T> initFunc) => _initFunc = initFunc;
  13. public T Instance
  14. {
  15. get
  16. {
  17. if (_heldInstance == null)
  18. {
  19. lock (_lock)
  20. {
  21. if (_heldInstance == null)
  22. {
  23. _heldInstance = _initFunc();
  24. }
  25. }
  26. }
  27. return _heldInstance;
  28. }
  29. }
  30. }
  31. }