先看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的更多相关文章

  1. HttpContext.Current.Cache 和 HttpRuntime.Cache 区别

    原文地址:http://blog.csdn.net/avon520/article/details/4872704 .NET中Cache有两种调用方式:HttpContext.Current.Cach ...

  2. 缓存 HttpContext.Current.Cache和HttpRuntime.Cache的区别

    先看MSDN上的解释: HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象. HttpRuntime.Cache:获取当前应用程序的Cache.  我们再用. ...

  3. HttpContext.Current.Cache 和HttpRuntime.Cache的区别

    先看MSDN上的解释:      HttpContext.Current.Cache:为当前 HTTP 请求获取Cache对象.      HttpRuntime.Cache:获取当前应用程序的Cac ...

  4. HttpContext.Current.Cache 和 HttpRuntime.Cache

    HttpRuntime.Cache:用于winfrom 和 web HttpContext.Current.Cache 用于web .NET中Cache有两种调用方式:HttpContext.Curr ...

  5. Cache及(HttpRuntime.Cache与HttpContext.Current.Cache)

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/avon520/archive/2009/11/25/4872704.aspx .NET中Cache有两种调用方式:Ht ...

  6. Asp.Net framework 类库 自带的缓存 HttpRuntime.Cache HttpContext.Cache

    两个Cache 在.NET运用中经常用到缓存(Cache)对象.有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序 ...

  7. ASP.NET HttpRuntime.Cache缓存类使用总结

    1.高性能文件缓存key-value存储—Redis 2.高性能文件缓存key-value存储—Memcached 备注:三篇博文结合阅读,简单理解并且使用,如果想深入学习,请多参考文章中给出的博文地 ...

  8. HttpRuntime.Cache

    a.在Web开发中,我们经常能够使用到缓存对象(Cache),在ASP.NET中提供了两种缓存对象,HttpContext.Current.Cache和HttpRuntime.Cache,那么他们有什 ...

  9. HttpRuntime.Cache .Net自带的缓存类

    .Net自带的缓存有两个,一个是Asp.Net的缓存 HttpContext.Cache,一个是.Net应用程序级别的缓存,HttpRuntime.Cache. MSDN上有解释说: HttpCont ...

随机推荐

  1. redis安装优化:

    1)内存分配控制: vm.overcommit_memoryredis启动时肯呢个会出现这样的日志: :M Apr ::! Background save may fail under low mem ...

  2. React Native集成Redux框架讲解与应用

    学过React Native的都知道,RN的UI是根据相应组件的state进行render的,而页面又是由大大小小的组件构成,导致每个组件都必须维护自身的一套状态,因此当页面复杂化的时候,管理stat ...

  3. shell脚本实现进度条

    使用shell脚本编写进度条 可已加入到shell脚本当中 主要作用:好看 美观 没毛用 (一) 普通进度条: #!/bin/bashb='' for ((i=0;$i<=20;i++)) do ...

  4. CVE补丁安全漏洞【学习笔记】

    更新安卓系统的CVE补丁网站:https://www.cvedetails.com/vulnerability-list/vendor_id-1224/product_id-19997/version ...

  5. Java JDBC概要总结一(基本操作和SQL注入问题)

    JDBC定义: JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API.JDBC是Java访问数据库的标准规范,可以为不同的关系 ...

  6. spring security使用hibernate进行查询数据库验证

    前面查询数据库采用的都是jdbc方式,如果系统使用的是hibernate,该如何进行呢,下面就是实现步骤,关键还是实现自定义的UserDetailsService 项目结构如下: 使用hibernat ...

  7. CocoaPods学习系列3——创建和使用私有Pods

    前一篇记录了使自己的项目支持CocoaPods管理的过程,核心的步骤就是podspec的配置和提交.这个文件,记录了类库的详细信息,用于对类库的集成. 需要注意的一点,上一篇创建的podspec文件, ...

  8. Android -- junit测试框架,logcat获取log信息

    1. 相关概念 白盒测试: 知道程序源代码. 根据测试的粒度分为不同的类型   方法测试 function test         单元测试 unit test                 集成 ...

  9. NFV及vIMS的部署实施

    随着5G和物联网等领域的快速发展,移动数据业务飞速增长,而传统电信网络基于专用硬件的架构和封闭式的网元,已经成为运营商拓展新业务的严重障碍.NFV能够根据用户和业务需求灵活动态地进行网络资源配置,实现 ...

  10. ndk+opencv安装+各种错误分析(新版安装,编译不需要Cygwin 和Sequoyah了)

    鼓捣了两三天,终于成功算跑通了一个简单的程序.下面说说具体的安装: 因为从同学那里拷过来的eclipse 就有adt cdt 的插件.所以这两个就不用再安装了.(需要的话自己安装) 具体说下安装过程: ...