您的位置:首页 > 编程语言 > ASP

[笔记] ASP.NET本身的缓存实现机制,基于Cache的实现。提供按分类进行管理的缓存功能

2008-08-28 14:34 986 查看
1. 申明一个Cache

private static Cache cache = HttpRuntime.Cache;

2. 往Cache内插入值

  cache.Insert(CreateKey(category, key), value, null, Cache.NoAbsoluteExpiration, TimeSpan.Zero);

3 读取Cache类的值

   /// <summary>

/// 获取缓存项

/// </summary>

/// <param name="category">缓存所属分类</param>

/// <param name="key">键</param>

/// <returns>缓存项</returns>

public static object GetValue(string category, string key)

{

return cache[CreateKey(category, key)];

}

  4 清除Cache内的值

 

  //全部清除Cache内的值

   if (cache.Count == 0)

{

//没有缓存项,直接返回

return;

}

lock (cache)

{

List<string> list = new List<string>();

var enumerator = cache.GetEnumerator();

string key = null;

while (enumerator.MoveNext())

{

key = enumerator.Key.ToString();

list.Add(key);

}

list.ForEach(item => cache.Remove(item));

}  

    

    //清除指定的Cache内的值

    lock (cache)

{

var enumerator = cache.GetEnumerator();

List<string> list = new List<string>(cache.Count);

string key = null;

while (enumerator.MoveNext())

{

key = enumerator.Key.ToString();

if (key.StartsWith(start))

{

//以所属分类作为开头的键符合清除条件

list.Add(key);

}

}

list.ForEach(item => cache.Remove(item));

} 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐