【渐进】延迟加载机制的简易实现(上)
2010-09-30 21:05:39 来源:WEB开发网接着要设计主要的加载器,作为这个机制的调用入口:
/// <summary>
/// 一级缓存容器
/// </summary>
internal class PrimaryCache : Dictionary<object, Dictionary<string, object>> { }
以上将作为一个缓存容器,后面会发掘出其他用途。
/// <summary>
/// 延?加?器
/// </summary>
public class LazyLoader
{
/// <summary>
/// 一级缓存
/// </summary>
private static PrimaryCache _pool = new PrimaryCache();
/// <summary>
/// 执?延?加?
/// ?声明了NotLazyScope?在声明有效?围内将执??延?加?
/// </summary>
/// <typeparam name="TIn">执?加?的对?类型</typeparam>
/// <typeparam name="TOut">加?的类型</typeparam>
/// <param name="loader">加?所使用的接口实例</param>
/// <param name="t">执?加?的对?实例</param>
/// <param name="property">延?加?的属性名称</param>
/// <returns>?回上一次加?结果</returns>
public static TOut Load<TIn, TOut>(ILoader<TOut, TIn> loader, TIn t, string property)
where TOut : class, new()
where TIn : class, new()
{
if (Exist<TIn>(t, property))
return _pool[t][property] as TOut;
lock (_pool)
{
if (!Exist<TIn>(t, property))
{
if (Lazy())
return default(TOut);
TOut result = loader.Load(t);
if (!_pool.ContainsKey(t))
_pool.Add(t, new Dictionary<string, object>());
_pool[t].Add(property, result);
}
}
return Lazy() ? default(TOut) : loader.Load(t);
}
/// <summary>
/// 是否存在缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="property"></param>
/// <returns></returns>
private static bool Exist<TIn>(TIn t, string property)
{
return _pool.ContainsKey(t) && _pool[t].ContainsKey(property);
}
/// <summary>
/// 是否延?
/// </summary>
/// <returns></returns>
private static bool Lazy()
{
return !Convert.ToBoolean(Thread.GetData(Thread.GetNamedDataSlot(NotLazyScope.SLOT_NAME)));
}
}
- ››延迟着色〔1〕
- ››延迟着色(2)
- ››加载XX.dll时出错的一般解决方法
更多精彩
赞助商链接