我想知道哪种方法以线程安全的方式加载数据更好。传统上,我使用了双锁模式,这很好地达到了目的。现在,随着 System.Lazy 类型的添加,我想知道依赖 Lazy 和 Loading 的内部结构是否更好,并以更好的方式完成工作。它看起来确实更干净,更容易阅读,但它更好吗?
有什么想法吗?
namespace SomeNameSpace
{
public class DataStoreContext
{
private readonly static Lazy<DataStoreContext> context = new Lazy<DataStoreContext>(() => new DataStoreContext());
private Lazy<Dictionary<string, Entity>> _entities = new Lazy<Dictionary<string, Entity>>(() => { return DataStoreContext.Instance.Load(); });
private readonly object _syncRoot = new object();
private DataStoreContext()
{
}
public Dictionary<string, Entity> Data
{
get { return _entities.Value; }
}
public static DataStoreContext Instance
{
get { return context.Value; }
}
private Dictionary<string, Entity> Load()
{
// Load Data from some data store.
return null;
}
private Dictionary<string, Entity> LoadWithLock()
{
if (_entities == null)
{
lock (_syncRoot)
{
if (_entities == null)
{
Dictionary<string, Entity> entities = this.Load();
_entities = entities;
return _entities;
}
}
}
return _entities ;
}
public void Clear()
{
_entities = new Lazy<Dictionary<string, Entity>>(() => { return DataStoreContext.Instance.Load(); });
}
}
}