参考该博主的:https://www.cnblogs.com/iiwen/p/4242185.html
博主总结的挺好,拿来分享:
先看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应用。
下面通过两个实例来说明HttpRuntime.Cache及HttpContext.Current.Cache用法区别:
1.控制台应用程序
static void Main(string[] args)
{
#region HttpRuntime.Cache ,HttpContext.Current.Cache 区别
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相当于就是一个缓存具体实现类,这个类虽然被放在了System.Web命名空间下,
但是非Web应用下也是可以使用;HttpContext.Current.Cache是对上述缓存类的封装,
由于封装到了HttpContext类中,局限于只能在知道HttpContext下使用,即只能用于Web应用。
*
* ***/
#endregion
#region HttpContext.Current.Cache使用
//显示所有缓存
string caches = ShowCache();
Console.WriteLine("获取缓存信息:" + caches);
//添加缓存
AddCacheStr("COMPANY","真兰信息技术有限公司");
//再次获取缓存
caches = ShowCache();
Console.WriteLine("获取缓存信息:" + caches);
//object obj = GetCache("COMPANY");
string cacheValue = GetMedthodSouceStr("COMPANY");
#endregion
}
顺便附上HttpContext.Current.Cache 自带的CRUD方法
#region HttpContext.Current.Cache用法1
//添加缓存datatable
public static void AddCacheDt(string key, DataTable dt)
{
if (System.Web.HttpContext.Current != null)
{
System.Web.HttpContext.Current.Cache.Insert(key, dt);
}
}
//添加缓存字符串
public static void AddCacheStr(string key, string str)
{
if (System.Web.HttpContext.Current != null)
{
System.Web.HttpContext.Current.Cache.Insert(key, str);
}
}
//添加缓存对象
public static void AddCacheStrObj(string key, Dictionary<string, string> strList)
{
if (System.Web.HttpContext.Current != null)
{
System.Web.HttpContext.Current.Cache.Insert(key, strList);
}
}
//获取datatable
public static DataTable GetMedthodSouceDt(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
DataTable dt = new DataTable();
dt = System.Web.HttpContext.Current.Cache[key] as DataTable;
return dt;
}
else
{
return null;
}
}
//获取字符串
public static string GetMedthodSouceStr(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
string result = string.Empty;
result = System.Web.HttpContext.Current.Cache[key].ToString();
return result;
}
else
{
return string.Empty;
}
}
//获取键值对
public static Dictionary<string, string> GetSqlAll(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
Dictionary<string, string> tpms = new Dictionary<string, string>();
tpms = System.Web.HttpContext.Current.Cache[key] as Dictionary<string, string>;
return tpms;
}
else
{
return null;
}
}
//获取指定的Cache
public static object GetCache(string key)
{
return System.Web.HttpContext.Current.Cache.Get(key);
}
//删除指定的Cache
public static void ClearCache(string key)
{
System.Web.HttpContext.Current.Cache.Remove(key);
}
//显示所有缓存
public static string ShowCache()
{
string str = "";
IDictionaryEnumerator CacheEnum = System.Web.HttpRuntime.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
str += "<br />缓存名<b>[" + CacheEnum.Key + "]</b><br />";
}
return "当前网站总缓存数:" + System.Web.HttpRuntime.Cache.Count + "<br />" + str;
}
#region 清除所有缓存
/// <summary>
/// 有时可能需要立即更新,这里就必须手工清除一下Cache
///Cache类有一个Remove方法,但该方法需要提供一个CacheKey,但整个网站的CacheKey我们是无法得知的
///只能经过遍历
/// </summary>
public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = System.Web.HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
_cache.Remove(key);
}
}
#endregion
#endregion
#region HttpRuntime.Cache用法 https://blog.csdn.net/weixin_44629250/article/details/88817948?utm_medium=distribute.pc_relevant_bbs_down.none-task--2~all~first_rank_v2~rank_v29-1.nonecase&depth_1-utm_source=distribute.pc_relevant_bbs_down.none-task--2~all~first_rank_v2~rank_v29-1.nonecase
/// 获取数据缓存
public static object GetCacheRuntime(string CacheKey)
{
System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
return objCache[CacheKey];
}
/// 设置数据缓存
public static void SetCache(string CacheKey, object objObject)
{
System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject);
}
/// 设置数据缓存
public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
{
System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
}
/// 设置数据缓存
public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
System.Web.Caching.Cache objCache = System.Web.HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
}
/// 移除指定数据缓存
public static void RemoveAllCache(string CacheKey)
{
System.Web.Caching.Cache _cache = System.Web.HttpRuntime.Cache;
_cache.Remove(CacheKey);
}
/// 移除全部缓存
public static void RemoveAllCaches()
{
System.Web.Caching.Cache _cache = System.Web.HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
_cache.Remove(CacheEnum.Key.ToString());
}
}
#endregion
#region 缓存项移除优先级: 指定 Cache 对象中存储的项的相对优先级。
public enum CacheItemPriority
{
// 在服务器释放系统内存时,具有该优先级级别的缓存项最有可能被从缓存删除。
Low = 1,
// 在服务器释放系统内存时,具有该优先级级别的缓存项比分配了 CacheItemPriority.Normal
// 优先级的项更有可能被从缓存删除。
BelowNormal = 2,
// 在服务器释放系统内存时,具有该优先级级别的缓存项很有可能被从缓存删除,
// 其被删除的可能性仅次于具有 CacheItemPriority.Low
// 或 CacheItemPriority.BelowNormal 优先级的那些项。这是默认选项。
Normal = 3,
// 缓存项优先级的默认值为 CacheItemPriority.Normal。
Default = 3,
// 在服务器释放系统内存时,具有该优先级级别的缓存项被删除的可能性
// 比分配了 CacheItemPriority.Normal 优先级的项要小。
AboveNormal = 4,
// 在服务器释放系统内存时,具有该优先级级别的缓存项最不可能被从缓存删除。
High = 5,
// 在服务器释放系统内存时,具有该优先级级别的缓存项将不会被自动从缓存删除。
// 但是,具有该优先级级别的项会根据项的绝对到期时间或可调整到期时间与其他项一起被移除。
NotRemovable = 6,
}
#endregion
2.webform应用程序
新增一个webform程序
protected void btnGetCache_Click(object sender, EventArgs e)
{
#region HttpContext.Current.Cache使用
//显示所有缓存
string caches = SystemCache.ShowCache();
txtCode.Text = caches;
//Console.WriteLine("获取缓存信息:" + caches);
//添加缓存
SystemCache.AddCacheStr("COMPANY", "***小兰信息技术有限公司");
//再次获取缓存
caches = SystemCache.ShowCache();
txtCode.Text = caches;
//Console.WriteLine("获取缓存信息:" + caches);
//object obj = GetCache("COMPANY");
string cacheValue = SystemCache.GetMedthodSouceStr("COMPANY");
txtCode.Text = cacheValue;
#endregion
}
封装的缓存操作方法:
public class SystemCache
{
//添加缓存datatable
public static void AddCacheDt(string key, DataTable dt)
{
if (System.Web.HttpContext.Current != null)
{
System.Web.HttpContext.Current.Cache.Insert(key, dt);
}
}
//添加缓存字符串
public static void AddCacheStr(string key, string str)
{
if (System.Web.HttpContext.Current != null)
{
//System.Web.HttpContext.Current.Cache.Insert(key, str);
DateTime nowTime = new DateTime();
nowTime = DateTime.Now;//当前时间后5分钟
DateTime after5Minutes = nowTime.AddMinutes(5);//当前时间后5分钟
TimeSpan sp = after5Minutes - nowTime;
System.Web.HttpContext.Current.Cache.Insert(key, str,null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));//设置5分钟后过期,所以当第一次设置缓存后,间隔5分钟后再获取就没有了
/*
* Cache.Insert(
string key,
object value,
CacheDependency dependencies,//依赖,设置缓存有效的依赖性,比如设置和一个文件相关,文件一变,就失效
DateTime absoluteExpireation, //设置固定的过期时间
TimeSpan slidingExpiration, //设置最后一次访问后多长时间过期
CachePriority priority, //设置内存不足,缓存自动清除时,缓存的重要性,可不可以清除
CacheItemRemovedCallback onRemoveCallback // 设置在清除时引发的事件
)
* **/
}
}
//添加缓存对象
public static void AddCacheStrObj(string key, Dictionary<string, string> strList)
{
if (HttpContext.Current != null)
{
System.Web.HttpContext.Current.Cache.Insert(key, strList);
}
}
//获取datatable
public static DataTable GetMedthodSouceDt(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
DataTable dt = new DataTable();
dt = System.Web.HttpContext.Current.Cache[key] as DataTable;
return dt;
}
else
{
return null;
}
}
//获取字符串
public static string GetMedthodSouceStr(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
string result = string.Empty;
result = System.Web.HttpContext.Current.Cache[key].ToString();
return result;
}
else
{
return string.Empty;
}
}
//获取键值对
public static Dictionary<string, string> GetSqlAll(string key)
{
if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Cache[key] != null)
{
Dictionary<string, string> tpms = new Dictionary<string, string>();
tpms = System.Web.HttpContext.Current.Cache[key] as Dictionary<string, string>;
return tpms;
}
else
{
return null;
}
}
//获取指定的Cache
public static object GetCache(string key)
{
return System.Web.HttpContext.Current.Cache.Get(key);
}
//删除指定的Cache
public static void ClearCache(string key)
{
System.Web.HttpContext.Current.Cache.Remove(key);
}
//显示所有缓存
public static string ShowCache()
{
string str = "";
IDictionaryEnumerator CacheEnum = System.Web.HttpRuntime.Cache.GetEnumerator();
while (CacheEnum.MoveNext())
{
str += "<br />缓存名<b>[" + CacheEnum.Key + "]</b><br />";
}
return "当前网站总缓存数:" + System.Web.HttpRuntime.Cache.Count + "<br />" + str;
}
#region 清除所有缓存
/// <summary>
/// 有时可能需要立即更新,这里就必须手工清除一下Cache
///Cache类有一个Remove方法,但该方法需要提供一个CacheKey,但整个网站的CacheKey我们是无法得知的
///只能经过遍历
/// </summary>
public static void RemoveAllCache()
{
System.Web.Caching.Cache _cache = System.Web.HttpRuntime.Cache;
IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
ArrayList al = new ArrayList();
while (CacheEnum.MoveNext())
{
al.Add(CacheEnum.Key);
}
foreach (string key in al)
{
_cache.Remove(key);
}
}
#endregion
}