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 == 0 ? new TimeSpan(0, 5, 0) : new TimeSpan(0, durationMin, 0);//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(0, 1, 0);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

转载于:https://www.cnblogs.com/mq0036/p/7016677.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/400677.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HIVE 一行转多行输出办法

2019独角兽企业重金招聘Python工程师标准>>> 1.问题描述 hive UDF 格式&#xff1a;oc号1_an号1_次数;oc号2_an号2_次数 转换结果&#xff1a; oc号1 an号1 次数 oc号2 an号2 次数 一行转多行&#xff0c;一行转多列 2.实现思路 第一步分割&#xff1a;split(oc号…

javascript/jquery获取图片的原始大小

实际生产过程中&#xff0c;我们往往有需要获得一个被压缩的图片的真实原始大小。此时我们可以用下面这个代码来实现&#xff1a; [js] // Get on screen image var screenImage $("#image"); // Create new offscreen image to test var theImage new Image(); th…

【机器视觉学习笔记】直方图的绘制及直方图均衡化(C++)

目录概念直方图定义直方图均衡化为什么要选用累积分布函数如何运用累积分布函数使得直方图均衡化C 源码直方图均衡化绘制直方图主函数效果完整源码平台&#xff1a;Windows 10 20H2 Visual Studio 2015 OpenCV 4.5.3 本文综合自直方图计算和程序员-图哥——图像处理之直方图均…

盒模型

CSSDIV 将数据封装到div中&#xff0c;页面中都是有很多div组成的&#xff0c;通过css布局(通过css属性布局)完成这些div位置的存放&#xff0c;一个div就是一个盒子。 边框   border:{ --left --right --top --bottom }; #div_1{ border-top:1px solid #ccc; border-bottom:…

C/C++ 如何劫持别人家的命令||函数||程序(只能对于window而言)

要实现下面程序&#xff0c;首先我们需要三个文件 detours.h &#xff0c;detours.lib &#xff0c;detver.h&#xff08;可以去网上下载&#xff09; 1. 首先让我们看看&#xff0c;一个最简单的C程序&#xff0c;如何劫持system函数. 1 #include<stdio.h>2 #include<…

【机器视觉学习笔记】伽马变换(C++)

目录概念C源码变换函数主函数效果完整源码平台&#xff1a;Windows 10 20H2 Visual Studio 2015 OpenCV 4.5.3 本文内容节选自《数字图像处理》第三版 C源码修改自C数字图像处理&#xff08;1&#xff09;-伽马变换 —— 图像大师 概念 C源码 变换函数 //函数名&#xff1…

soapui自带的webservice实例 MockService

soapui自带的webservice实例 & MockService&#xff1a; http://www.docin.com/p-646423228.html 转载于:https://www.cnblogs.com/preftest/archive/2013/05/09/3070243.html

数据库和数据挖掘领域的会议和期刊

数据库和数据挖掘领域的会议和期刊数据库领域主要专注于数据库系统和数据管理算法&#xff0c;而数据挖掘主要是专注于数据价值分析算法。一、数据库领域的主要会议数据库领域的顶级会议SIGMOD、ICDE、VLDB&#xff0c;下面将对这三大会议进行一下简单介绍。 SIGMOD-----------…

lxml库的基本使用

Python之lxml模块的使用&#xff1a;1. 认识lxml2. lxml中基本使用2.1 安装并导入lxml模块2.2 节点操作&#xff1a;2.3 属性操作&#xff1a;2.4 文本操作2.5 xml文件解析与序列化2.6 lxml命名空间的处理3. 使用lxml解析xml案例4. 使用lxml生成一个xml文件案例&#xff1a;5. …

Linux文件查找之find秘笈

前言Linux的基本特点之一是一切皆文件&#xff0c;在系统管理过程中难免会需要查找特定类型的文件&#xff0c;那么问题来了&#xff1a;如何进行有效且准确的查找呢&#xff1f;本文将对Linux系统中的文件查找工具及用法进行详细讲解。常用工具对比常用的文件查找工具主要有lo…

【机器视觉学习笔记】大津法/Otsu最大类间方差法 最佳阈值处理(C++)

目录概念C源码OtsuThreshold主函数效果完整源码平台&#xff1a;Windows 10 20H2 Visual Studio 2015 OpenCV 4.5.3 本文所用源码修改自C opencv 图片二值化最佳阈值确定&#xff08;大津法,OTSU算法)——Sharon Liu 概念 Otsu算法&#xff0c;也叫最大类间方差法&#xff0…

HTML 页面源代码布局介绍

此介绍以google首页源代码截图为例&#xff1a; 从上到下依次介绍&#xff1a; 1.<!DOCTYPE html> 此标签可告知浏览器文档使用哪种 HTML 或 XHTML 规范。 XHTML规范&#xff1a;必须小写&#xff0c;有开始结束标签&#xff0c;属性也用双引号。 HTML规范&#xff1a;不…

Python对Protobuf进行序列化与反序列化

Python Protobuf1.了解Protobuf&#xff1a;1.1 Protobuf语法介绍&#xff1a;2. Python使用Protobuf&#xff1a;(windows平台上)1.了解Protobuf&#xff1a; 我们在使用protobuf之前首先要了解protobuf&#xff0c;那么什么是protobuf呢&#xff1f; 官方的解释是&#xff…

sql server management studio 查询的临时文件路径

C:\Users\你的登录名称\Documents\SQL Server Management Studio\Backup FilesC:\Users\你的登录名称\AppData\Local\Temp\sql server management studio 非正常关闭时自动保存的路径在sql server management studio 里创建的“新建查询”且没有手动保存的路径转载于:https://w…

Linux下如何自己编译源代码(制作成可以安装的.deb文件)

以tree实用程序&#xff08;以树型结构获取目录树&#xff09;为例&#xff0c;介绍Ubuntu中如何管理源码包&#xff0c;包括查询&#xff0c;获取&#xff0c;编译源码包&#xff0c;直至安装。1&#xff09; 在获取源码包之前&#xff0c;确保在软件源配置文件/etc/apt/sourc…

K210 / Openmv实现 大津法/Otsu最大类间方差法 自适应二值化

目录源码效果平台&#xff1a;K210 固件版本&#xff1a;maixpy_v0.6.2_54_g897214100_openmv_kmodel_v4_with_ide_support.bin OpenMv库自带Otsu算法: 源码 # Otsu.py - By: Royic - 周三 9月 22 2021import sensor, imagesensor.reset() sensor.set_pixformat(sensor.GRAY…

第一章:OpenCV入门

第一章&#xff1a;OpenCV入门 OpenCV是一个开源的计算机视觉库&#xff0c;1999年有英特尔的Gary Bradski启动。OpenCV库由C和C语言编写&#xff0c;涵盖计算机视觉各个领域内的500多个函数&#xff0c;可以在多个操作系统上运行。它旨在提供一个简洁而又高效的接口&#xff…

神奇的vfork

一段神奇的代码在论坛里看到下面一段代码&#xff1a;int createproc();int main(){pid_t pidcreateproc();printf("%d\n", pid);exit(0);}int createproc(){pid_t pid;if(!(pidvfork())) {printf("child proc:%d\n", pid);return pid;}else return -1;}输…

18、Java并发性和多线程-饥饿与公平

以下内容转自http://ifeve.com/starvation-and-fairness/&#xff1a; 如果一个线程因为CPU时间全部被其他线程抢走而得不到CPU运行时间&#xff0c;这种状态被称之为“饥饿”。而该线程被“饥饿致死”正是因为它得不到CPU运行时间的机会。解决饥饿的方案被称之为“公平性”–即…

OpenSceneGraph 3.2 版本修改点

OpenSceneGraph-3.2.0稳定版本发布了&#xff0c;改善了对iOS、Android的支持&#xff0c;支持OpenGL的更多新特性。可以通过 下载版块来进行下载。 OpenSceneGraph 3.2 发布. 版本修改点: 全面对OpenGL ES 1.1 和 2.0 的支持&#xff0c;包括各种扩展。改善QTKit, imageio 以及…