HttpContext.Current.Cache和HttpRuntime.Cache的区别,以及System.Runtime.Caching
先看MSDN上的解释:
HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象。
HttpRuntime.Cache:获取当前应用程序的Cache。
我们再用.NET Reflector工具看看HttpContext.Cache和HttpRuntime.Cache的实现:
HttpContext.Cache和HttpRuntime.Cache实现
//System.Web.HttpContext.Cache属性实现
public sealed class HttpContext
{
public Cache Cache
{
get
{
return HttpRuntime.Cache;
}
}
}
//System.Web.HttpRuntime.Cache属性实现
public sealed class HttpRuntime
{
public static Cache Cache
{
get
{
if (AspInstallDirectoryInternal == null)
{
throw new HttpException(SR.GetString("Aspnet_not_installed", new object[] { VersionInfo.SystemWebVersion }));
}
Cache cache = _theRuntime._cachePublic;
if (cache == null)
{
CacheInternal cacheInternal = CacheInternal;
CacheSection cacheSection = RuntimeConfig.GetAppConfig().Cache;
cacheInternal.ReadCacheInternalConfig(cacheSection);
_theRuntime._cachePublic = cacheInternal.CachePublic;
cache = _theRuntime._cachePublic;
}
return cache;
}
}
}
通过上面的代码我们可以看出:HttpContext.Current.Cache是调用HttpRuntime.Cache实现的,两者指向同一Cache对象。那么两者到底有没有区别的?既然两个指向的是同一Cache对象,两者的差别只能出现在HttpContext和HttpRuntime上了。我们再来看看MSDN中HttpContext和HttpRuntime的定义。
HttpContext:封装有关个别HTTP请求的所有HTTP特定的信息,HttpContext.Current为当前的HTTP请求获取HttpContext对象。
HttpRuntime:为当前应用程序提供一组ASP.NET运行时服务。
由上面的定义可以看出:HttpRuntime.Cache相当于就是一个缓存具体实现类,这个类虽然被放在了System.Web命名空间下,但是非Web应用下也是可以使用;HttpContext.Current.Cache是对上述缓存类的封装,由于封装到了HttpContext类中,局限于只能在知道HttpContext下使用,即只能用于Web应用。
下面的例子可以很好的说明这一点:
HttpContext.Cache和HttpRuntime.Cache的示例
class CacheTest
{
static void Main(string[] args)
{
System.Web.Caching.Cache httpRuntimeCache = System.Web.HttpRuntime.Cache;
httpRuntimeCache.Insert("httpRuntimeCache", "I am stored in HttpRuntime.Cache");
if (httpRuntimeCache != null)
{
Console.WriteLine("httpRuntimeCache:" + httpRuntimeCache["httpRuntimeCache"]);
}
System.Web.HttpContext httpContext = System.Web.HttpContext.Current;
if (httpContext == null)
{
Console.WriteLine("HttpContext object is null in Console Project");
}
else
{
System.Web.Caching.Cache httpContextCache = httpContext.Cache;
httpContextCache.Insert("httpContextCache", "I am stored in HttpRuntime.Cache");
if (httpContextCache == null)
{
Console.WriteLine("httpContextCache is null");
}
}
Console.ReadLine();
}
}
输出结果:httpRuntimeCache:I am stored in HttpRuntime.Cache
HttpContext object is null in Console Project
综上:我们在使用Cache时,尽量使用HttpRuntime.Cache,既能减少出错,也减少了一次函数调用。
参考资料:HttpRuntime.Cache 与HttpContext.Current.Cache的疑问,HttpRuntime.Cache vs. HttpContext.Current.Cache
出处:http://blog.csdn.net/qwlovedzm/article/details/7024405
===============================================================================
下面我们看看简单的缓存类处理:
using System;
using System.Collections;
using System.Web;
using System.Web.Caching; namespace aaaaa.Api.Business
{
/// <summary>
/// 缓存类
/// </summary>
public class CacheHelper
{
/// <summary>
/// 增加一个缓存对象
/// </summary>
/// <param name="strKey">键值名称</param>
/// <param name="valueObj">被缓存对象</param>
/// <param name="durationMin">缓存失效时间(默认为5分钟)</param>
/// <param name="cachePriority">保留优先级(枚举数值)</param>
/// <returns>缓存写入是否成功true 、false</returns>
public static bool InsertCach(string strKey, object valueObj, int durationMin,
CacheItemPriority cachePriority = CacheItemPriority.Default)
{
TimeSpan ts;
if (!string.IsNullOrWhiteSpace(strKey) && valueObj != null)
{
//onRemove是委托执行的函数,具体方法看下面的onRemove(...)
CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove);
ts = durationMin == ? new TimeSpan(, , ) : new TimeSpan(, durationMin, );
//HttpContext.Current.Cache.Insert(
HttpRuntime.Cache.Insert(
strKey,
valueObj,
null,
DateTime.Now.Add(ts),
Cache.NoSlidingExpiration,
cachePriority,
callBack
);
return true;
}
else
{
return false;
}
} /// <summary>
/// 判断缓存对象是否存在
/// </summary>
/// <param name="strKey">缓存键值名称</param>
/// <returns>是否存在true 、false</returns>
public static bool IsExist(string strKey)
{
//return HttpContext.Current.Cache[strKey] != null;
return HttpRuntime.Cache.Get(strKey) != null;
} /// <summary>
/// 读取缓存对象
/// </summary>
/// <param name="strKey">缓存键值名称</param>
/// <returns>缓存对象,objec类型</returns>
public static object GetCache(string strKey)
{
//if (HttpContext.Current.Cache[strKey] != null)
if (IsExist(strKey))
{
object obj = HttpRuntime.Cache.Get(strKey);
return obj ?? null;
}
else
{
return null;
}
} /// <summary>
/// 移除缓存对象
/// </summary>
/// <param name="strKey">缓存键值名称</param>
public static void Remove(string strKey)
{
//if (HttpContext.Current.Cache[strKey] != null)
if (IsExist(strKey))
{
HttpRuntime.Cache.Remove(strKey);
}
} /// <summary>
/// 清除所有缓存
/// </summary>
public static void Clear()
{
IDictionaryEnumerator enu = HttpRuntime.Cache.GetEnumerator();
while (enu.MoveNext())
{
Remove(enu.Key.ToString());
}
} public static CacheItemRemovedReason reason;
/// <summary>
/// 此方法在值失效之前调用,可以用于在失效之前更新数据库,或从数据库重新获取数据
/// </summary>
/// <param name="strKey"></param>
/// <param name="obj"></param>
/// <param name="reason"></param>
private static void onRemove(string strKey, object obj, CacheItemRemovedReason r)
{
reason = r;
} //... }
}
出处:http://blog.csdn.net/joyhen/article/details/40379145
=======================================================================
引用:System.Runtime.Caching.dll,如下测试,fm4.5
static void CacheTest()
{
string cname = "filescontents";
ObjectCache cc = MemoryCache.Default;
string fileContents = cc[cname] as string; if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy(); TimeSpan sp = new TimeSpan(, , );
policy.SlidingExpiration = sp; List<string> filePaths = new List<string>();
string path = System.IO.Directory.GetCurrentDirectory() + "\\example.txt";
filePaths.Add(path); policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths)); fileContents = System.IO.File.ReadAllText(path, Encoding.Default);
cc.Set(cname, fileContents, policy);
} Console.WriteLine(fileContents);
} static void Main(string[] args)
{
//ExecuteCode(WriteData);
//ExecuteCode(ReadData);
//ExecuteCode(TransData);
bool quit = false;
while (!quit)
{
Console.Write("get cache: ");
string demo = Console.ReadLine();
switch (demo)
{
case "Y": ExecuteCode(CacheTest); break;
case "Q":
quit = true;
break;
default:
Console.WriteLine("Choose a Word of Y and Q(to quit)");
break;
}
}
Console.ReadKey();
} public static void ExecuteCode(Action a)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start(); a(); stopwatch.Stop();
TimeSpan timespan = stopwatch.Elapsed; Console.WriteLine("运行{0}秒", timespan.TotalSeconds);
}
出处:http://blog.csdn.net/joyhen/article/details/39990455
HttpContext.Current.Cache和HttpRuntime.Cache的区别,以及System.Runtime.Caching的更多相关文章
- HttpContext.Current.Cache 和 HttpRuntime.Cache 区别
原文地址:http://blog.csdn.net/avon520/article/details/4872704 .NET中Cache有两种调用方式:HttpContext.Current.Cach ...
- 缓存 HttpContext.Current.Cache和HttpRuntime.Cache的区别
先看MSDN上的解释: HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象. HttpRuntime.Cache:获取当前应用程序的Cache. 我们再用. ...
- HttpContext.Current.Cache 和HttpRuntime.Cache的区别
先看MSDN上的解释: HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象. HttpRuntime.Cache:获取当前应用程序的Cac ...
- HttpContext.Current.Cache 和 HttpRuntime.Cache
HttpRuntime.Cache:用于winfrom 和 web HttpContext.Current.Cache 用于web .NET中Cache有两种调用方式:HttpContext.Curr ...
- Cache及(HttpRuntime.Cache与HttpContext.Current.Cache)
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/avon520/archive/2009/11/25/4872704.aspx .NET中Cache有两种调用方式:Ht ...
- Asp.Net framework 类库 自带的缓存 HttpRuntime.Cache HttpContext.Cache
两个Cache 在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序 ...
- ASP.NET HttpRuntime.Cache缓存类使用总结
1.高性能文件缓存key-value存储—Redis 2.高性能文件缓存key-value存储—Memcached 备注:三篇博文结合阅读,简单理解并且使用,如果想深入学习,请多参考文章中给出的博文地 ...
- HttpRuntime.Cache
a.在Web开发中,我们经常能够使用到缓存对象(Cache),在ASP.NET中提供了两种缓存对象,HttpContext.Current.Cache和HttpRuntime.Cache,那么他们有什 ...
- HttpRuntime.Cache .Net自带的缓存类
.Net自带的缓存有两个,一个是Asp.Net的缓存 HttpContext.Cache,一个是.Net应用程序级别的缓存,HttpRuntime.Cache. MSDN上有解释说: HttpCont ...
随机推荐
- MySQL二进制日志文件过期天数设置说明
今天在处理业务库中二进制文件的时候,想更改二进制文件的过期天数,发现日期如果设置成2位以上的整数.都会出现如下的警告.不能成功的设置过期日期天数.MySQL版本从5.1到5.5都是一样的. mysql ...
- Linux 设备驱动之 UIO 机制
一个设备驱动的主要任务有两个: 1. 存取设备的内存 2. 处理设备产生的中断 对于第一个任务.UIO 核心实现了mmap()能够处理物理内存(physical memory),逻辑内存(logica ...
- php中POST与GET区别
如果有人问你,GET和POST,有什么区别?你会如何回答? 我的经历 前几天有人问我这个问题.我说GET是用于获取数据的,POST,一般用于将数据发给服务器之用. 这个答案好像并不是他想要的.于是他继 ...
- Spark 宽窄依赖
面试时被问到spark RDD的宽窄依赖,虽然问题很简单,但是答得很不好.还是应该整理一下描述,这样面试才能答得更好. 看到一篇很好的文章,转载过来了.感觉比<spark技术内幕>这本书讲 ...
- js进阶---12-10、jquery绑定事件和解绑事件是什么
js进阶---12-10.jquery绑定事件和解绑事件是什么 一.总结 一句话总结:on和off. 1.jquery如何给元素绑定事件? on方法 22 $('#btn1').on('click', ...
- Linux grep 命令大全
grep: 用于模糊查找,在标准输入或者文件中 格式: grep [选项参数]... PATTERN |FILE ... 选项参数说明: -E, --extended-regexp PATTERN ...
- Django进阶Model篇002 - 模型类的定义
一.创建数据模型. 实例: 作者模型:一个作者有姓名. 作者详情模型:把作者的详情放到详情表,包含性别.email 地址和出生日期,作者详情模型与作者模型之间是一对一的关系(OneToOneField ...
- srs部署到ubuntu 18.04 server
srs.txt ubuntu 18.04 安装 srs 1. 上传srs_40.7z和h2ws.7z到linux服务器,然后远程ssh连接 (假设登陆用户名是bob,linux服务器ip是192.16 ...
- Superset 初探
安装都是借鉴的别人的,已经剪裁下来.到自己文件夹里了. 下面介绍.如何启动superset ,BI 分析工具.这是我以前的强项.应该没问题. 问题: 安装好了之后,再打开localhost 就拒绝访问 ...
- flask 项目 部署服务器,package安装问题(无外网链接)
1.安装所需的环境/包 1) 在一台开发机器(有网络,编译成功)安装package: pipreqs 语法: pipreqs <项目路径> 将项目所使用的所有包目录将会导出至目录:requ ...