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 ...
随机推荐
- 20145219 《Java程序设计》实验二 Java面向对象程序设计实验报告
20145219 <Java程序设计>实验二 Java面向对象程序设计实验报告 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S. ...
- COS-4进程及进程管理
操作系统是用户和计算机的接口,同时也是计算机硬件和其他软件的接口.操作系统的功能包括管理计算机系统的硬件.软件及数据资源,控制程序运行,改善人机界面,为其它应用软件提供支持,让计算机系统所有资源最大限 ...
- 解析Linux系统的平均负载概念
一.什么是系统平均负载(Load average)? 在Linux系统中,uptime.w.top等命令都会有系统平均负载load average的输出,那么什么是系统平均负载呢?系统平均负载被定义为 ...
- 如何在深层嵌套ngRepeat中获取不同层级的$index
<ul class="list-group" ng-repeat="item in vm.appData" ng-init="outerInde ...
- yii2: 点击编辑后,左侧的连接(a.navtab)失效,变成在新窗口打开
如:图一 使用a.navtab的时候,点击[自定义回复]->右侧列表,随便编辑一个,完成后 图二: 再点击,左侧的菜单,打开iframe就会失败,直接在新窗口打开.源代码如下: 造成这样的原因是 ...
- javascript HTML DOM 简单介绍
JavaScript HTML DOM通过 HTML DOM,可访问 JavaScript HTML 文档的所有元素.HTML DOM (文档对象模型)当网页被加载时,浏览器会创建页面的文档对象模型( ...
- Linux文件夹权限详解
- 第一个字符代表文件(-).目录(d),链接(l) - 其余字符每3个一组(rwx),读(r).写(w).执行(x) - 第一组rwx:文件所有者的权限是读.写和执行 - 第二组rw-:与文件所有者 ...
- SpringCloud分布式开发理解
谈到SpringCloud最新接触到的可能就是那五大"神兽",之前最先接触分布式开发是通过dubbo的RPC远程过程调用,而dubbo给我得感觉就是:虽然所有的主机物理上分布了,但 ...
- 牛客比赛-状压dp
链接:https://www.nowcoder.com/acm/contest/74/F来源:牛客网 德玛西亚是一个实力雄厚.奉公守法的国家,有着功勋卓著的光荣军史. 这里非常重视正义.荣耀.职责的意 ...
- 【scala】语法的省略
我们直到JAVA在语法方面是冗长的,但是JAVA的可读性非常好. 在Scala的语法并不像JAVA那样冗长,但是又不失可读性,我们这里记录一下常见的语法省略. 首先是我们可以省略数据类型,因为Scal ...