缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别
生活随笔
收集整理的這篇文章主要介紹了
缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
以前寫asp.net時用HttpContext.Current.Cache存緩存很好用,今天寫了一個windows服務程序,HttpContext.Current.Cache存緩存的時候還好,取的時候一直報錯“未將對象引用到實例”很郁悶,查詢了一下資料才明白引用程序緩存要用HttpRuntime.Cache...
我們先看MSDN上的解釋:
??????HttpContext.Current.Cache:為當前 HTTP 請求獲取Cache對象。
?????? HttpRuntime.Cache:獲取當前應用程序的Cache。
附帶的寫了一個操作緩存的通用類,在應用程序中使用,如果要在asp.net中有,只需把HttpRuntime.Cache改為HttpContext.Current.Cache即可,代碼如下:
?
代碼 using System;/// <summary>
/// author:Stone_W
/// date:2010.12.1
/// desc:緩存的管理類
/// 注意:要添加對引用 System.Web
/// </summary>
public class MyCacheTools : System.Web.SessionState.IRequiresSessionState
{
#region 存入Cache
/// <summary>
/// 存入Cache
/// </summary>
/// <param name="key">緩存key</param>
/// <param name="value">緩存的值</param>
/// <param name="time_HH">存xx小時</param>
/// <returns>是否執行成功[bool]</returns>
public static bool SetCache(string key, object value, int time_HH)
{
bool result = false;
try
{
DateTime dt = DateTime.Now.AddHours(time_HH);
System.Web.HttpRuntime.Cache.Insert(key, value, null,
dt, System.Web.Caching.Cache.NoSlidingExpiration);
result = true;
}
catch (Exception ex) { }
return result;
}
#endregion
#region 取得Cache
/// <summary>
/// 取得Cache
/// </summary>
/// <param name="key">key</param>
/// <returns>object類型</returns>
public static object GetCache(string key)
{
return System.Web.HttpRuntime.Cache.Get(key);
}
#endregion
#region 查詢Cache是否存在
/// <summary>
/// 查詢Cache是否存在
/// </summary>
/// <param name="key">key 值</param>
/// <returns>bool</returns>
public static bool IsCacheExist(string key)
{
bool result = false;
object temp = System.Web.HttpRuntime.Cache.Get(key);
if (null != temp)
{
result = true;
}
return result;
}
#endregion
}
?
?
ps:HttpContext.Current.Cache 為null 這個問題搞的我很痛苦,最后還是解決了,希望此篇文章對大家有用!
?
總結
以上是生活随笔為你收集整理的缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vb中picturebox透明时看到下面
- 下一篇: pomelo获取客户端IP