日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别

發(fā)布時(shí)間:2025/3/11 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

  以前寫asp.net時(shí)用HttpContext.Current.Cache存緩存很好用,今天寫了一個(gè)windows服務(wù)程序,HttpContext.Current.Cache存緩存的時(shí)候還好,取的時(shí)候一直報(bào)錯(cuò)“未將對象引用到實(shí)例”很郁悶,查詢了一下資料才明白引用程序緩存要用HttpRuntime.Cache...

  我們先看MSDN上的解釋:

  ??????HttpContext.Current.Cache:為當(dāng)前 HTTP 請求獲取Cache對象。
??????  HttpRuntime.Cache:獲取當(dāng)前應(yīng)用程序的Cache。

附帶的寫了一個(gè)操作緩存的通用類,在應(yīng)用程序中使用,如果要在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小時(shí)</param>
/// <returns>是否執(zhí)行成功[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 這個(gè)問題搞的我很痛苦,最后還是解決了,希望此篇文章對大家有用!

?

總結(jié)

以上是生活随笔為你收集整理的缓存通用管理类 + 缓存 HttpContext.Current.Cache 和 HttpRuntime.Cache 的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。