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 ...
随机推荐
- MapReduce:实现文档倒序排序,且字符串拼接+年+月+日
写出MapReduce程序完成以下功能. input1: -- a -- b -- c -- d -- a -- b -- c -- c input2: -- b -- a -- b -- d -- ...
- iOS7中彻底隐藏status bar
用Xcode5开发新游戏,发现在iOS7中按照以前的方法隐藏status bar失效了. 想要彻底隐藏status bar,需要在info.plist中添加新行“View controller-bas ...
- 通过excel快速拼接SQL
“哎,发你一个excel,把这几百条数据修复喽.”经理喊道. “嗯,好的!” 正在看资料的我被经理临时分的任务打断,搞吧!这就是我平时中的一个工作场景. 工作中总是会遇到要修复数据,数据在excel中 ...
- 用adb 启动camera
adb shell am start -a android.media.action.STILL_IMAGE_CAMERA 启动camera adb shell input keyevent 27 ...
- JAVA基础补漏--继承
子类的对象在创建时,首先调用父类的构造函数,再调用子类自己的构造函数. 子类的构造函数中,有一个默认的super(),为一个无参调用,这个不显示,但会被首先调用,所有才会有父类构造函数被调用的情况. ...
- install tabix/bgzip
bgzip – Block compression/decompression utility tabix – Generic indexer for TAB-delimited genome pos ...
- AtCoder Regular Contest 097
AtCoder Regular Contest 097 C - K-th Substring 题意: 求一个长度小于等于5000的字符串的第K小子串,相同子串算一个. K<=5. 分析: 一眼看 ...
- nginx官网下载&百度云分享
官网下载的链接: nginx官网下载地址:http://nginx.org/download/ 百度云分享 链接:https://pan.baidu.com/s/16m6zrFSkYCJtX0rD2Y ...
- on绑定阻止冒泡失败
使用zepto库,有如下dom <div id="J_parent"> <a href="#"> <span>点我有惊喜&l ...
- Flume-NG中的Channel与Transaction关系(原创)
在sink和source中(不管是内置还是自定义的),基本都有如下代码,这些代码在sink中的process方法中,而在source中自己不需要去写,在source中getChannelProcess ...