使用APPLICATION制作缓存,转存一下,有一段写的还可以。
public sealed class CacheManager
{
private HttpApplicationState appPool = null;
/// <summary>
/// 构造函数
/// </summary>
public CacheManager()
{
this.appPool = HttpContext.Current.Application;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="application">HttpApplicationState 对象</param>
public CacheManager(HttpApplicationState application)
{
this.appPool = application;
}
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存名称</param>
public void Delete(string key)
{
this.appPool.Lock();
this.appPool.Remove(key);
this.appPool.Remove(key + "(expTime)");
this.appPool.UnLock();
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存名称</param>
/// <param name="value">缓存值</param>
/// <returns></returns>
public bool Add(string key, object value)
{
try
{
this.appPool.Lock();
this.appPool[key] = value;
this.appPool[key + "(expTime)"] = DateTime.MaxValue; // 这里设置一个最大时间值,直到Application结束。
this.appPool.UnLock();
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存名称</param>
/// <param name="value">缓存值</param>
/// <param name="expireTime">有效时间</param>
/// <returns></returns>
public bool Add(string key, object value, DateTime expireTime)
{
try
{
this.appPool.Lock();
this.appPool[key] = value;
this.appPool[key + "(expTime)"] = expireTime;
this.appPool.UnLock();
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存名称</param>
/// <returns></returns>
public object Get(string key)
{
object o = this.appPool.Get(key + "(expTime)");
if (o != null)
{
TimeSpan ts = (TimeSpan)(DateTime.Now - (DateTime)o);
if (ts.TotalSeconds < 0)
{
return this.appPool.Get(key);
}
else
{
this.Delete(key);
return null;
}