缓存通用管理类 + 缓存 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 这个问题搞的我很痛苦,最后还是解决了,希望此篇文章对大家有用!
关注下面二维码,订阅更多精彩内容。

【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验