123456789101112131415161718192021222324252627282930313233343536 |
- using System;
- namespace VCommon
- {
- /// <summary>
- /// 惰性初始化包裹, 线程安全
- /// </summary>
- public class LazyHolder<T> where T : class
- {
- private readonly object _lock = new object();
- private readonly Func<T> _initFunc;
- private T _heldInstance;
- public LazyHolder(Func<T> initFunc) => _initFunc = initFunc;
- public T Instance
- {
- get
- {
- if (_heldInstance == null)
- {
- lock (_lock)
- {
- if (_heldInstance == null)
- {
- _heldInstance = _initFunc();
- }
- }
- }
- return _heldInstance;
- }
- }
- }
- }
|