Asp.net中全局缓存的几种方式

public class StaticCacheTest

{

private static IDictionary<string, object> _dic;

private static object locker = new object();

private static IDictionary<string, object> CachedDic

{

get

{

if (_dic == null)

{

lock (locker)

{

if (_dic == null)

{

_dic = new Dictionary<string, object>();

}

}

}

return _dic;

}

}

public static object GetObject(string key)

{

return CachedDic[key];

}

public static void SetObject(string key, object obj)

{

lock (locker)

{

CachedDic[key] = obj;

}

}

}

public partial class _Default : System.Web.UI.Page

{

private const string KEY = "CurrentTime";

protected void Page_Load(object sender, EventArgs e)

{

String curTime = System.DateTime.Now.ToString();

if (HttpContext.Current.Application[KEY] == null)

{

HttpContext.Current.Application.Lock();
HttpContext.Current.Application[KEY] = curTime;
HttpContext.Current.Application.UnLock();
}

if (HttpContext.Current.Cache[KEY] == null)

{

HttpContext.Current.Cache.Insert(KEY, curTime);

}

if (StaticCacheTest.GetObject(KEY) == null) //本质上就是HttpRuntime.Cache的实现方式

{

StaticCacheTest.SetObject(KEY, curTime);

}

if (HttpRuntime.Cache[KEY] == null)

{

HttpRuntime.Cache.Insert(KEY, curTime); //HttpRuntime.Cache与HttpContext.Current.Cache是同一对象,建议使用HttpRuntime.Cache

}

TextBox1.Text = HttpContext.Current.Application[KEY].ToString();

TextBox2.Text=HttpContext.Current.Cache[KEY].ToString();

TextBox3.Text=StaticCacheTest.GetObject(KEY).ToString();

TextBox4.Text=System.Web.HttpRuntime.Cache.Get(Key).ToString();

}

}

------------------------------------------------------------------------------------------------

System.Web.HttpRuntime.Cache的方法:

Add

Insert

Get

Remove

缓存的操作包括:读、写。
读取缓存内容调用System.Web.HttpRuntime.Cache.Get(Key)方法,插入缓存数据调用Add或Insert方法。

Add与Insert的不同

HttpRuntime.Cache.Add 存在相同的键会异常,返回缓存成功的对象。

HttpRuntime.Cache.Insert存在相同的键会替换原值,无返回值。

如果您希望某个缓存项目一旦放入缓存后,就不要再被修改,那么调用Add确实可以防止后来的修改操作。而调用Insert方法,则永远会覆盖已存在项。

缓存的过期时间

缓存过期时间包括:绝对过期和滑动过期。

绝对过期:到了指定时间以后便会失效。

滑动过期:在指定时间内无访问请求便失效。

实例:

绝对过期:

HttpRuntime.Cache.Insert(key, value, null, DateTime.Now.AddSeconds(seconds),System.Web.Caching.Cache.NoSlidingExpiration);

滑动过期:

HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration
, TimeSpan.FromSeconds(seconds));

原文地址:https://www.cnblogs.com/mili3/p/4692240.html