1 借鉴这篇文章

https://www.cnblogs.com/zuowj/p/8440902.html

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Runtime.Caching;
  7. using System.Diagnostics;
  8.  
  9. namespace ConsoleApp1
  10. {
  11. public static class MemoryCacheHelper
  12. {
  13. private static readonly object _locker = new object();
  14. private static readonly object _locker2 = new object();
  15.  
  16. /// <summary>
  17. /// 根据key取缓存,不存在则返回null
  18. /// </summary>
  19. /// <typeparam name="T"></typeparam>
  20. /// <param name="key"></param>
  21. /// <returns></returns>
  22. public static T GetCacheItem<T>(String key)
  23. {
  24. try
  25. {
  26. return (T)MemoryCache.Default[key];
  27. }
  28. catch (Exception ex)
  29. {
  30.  
  31. return default(T);
  32. }
  33. }
  34.  
  35. /// <summary>
  36. /// 是否包含指定键的缓存项
  37. /// </summary>
  38. /// <param name="key"></param>
  39. /// <returns></returns>
  40. public static bool Contains(string key)
  41. {
  42. return MemoryCache.Default.Contains(key);
  43. }
  44.  
  45. public static T GetOrAddCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
  46. {
  47. if (string.IsNullOrWhiteSpace(key))
  48. {
  49. throw new ArgumentException("Invalid cache key");
  50. }
  51. if (cachePopulate == null)
  52. {
  53. throw new ArgumentException("cachePopulate");
  54. }
  55. if (slidingExpiration == null && absoluteExpiration == null)
  56. {
  57. throw new ArgumentException("Either a sliding expiration or absolute must be provided");
  58. }
  59. if (MemoryCache.Default[key] == null)
  60. {
  61. lock (_locker)
  62. {
  63. if (MemoryCache.Default[key] == null)
  64. {
  65. T cacheValue = cachePopulate();
  66. if (!typeof(T).IsValueType && ((object)cacheValue) == null)
  67. {
  68. return cacheValue;
  69. }
  70. var item = new CacheItem(key, cacheValue);
  71. var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
  72. MemoryCache.Default.Add(item, policy);
  73. }
  74.  
  75. }
  76. }
  77.  
  78. return (T)MemoryCache.Default[key];
  79. }
  80.  
  81. public static T GetOrAddCacheItem<T>(string key,Func<T> cachePopulate,string dependencyFilePath)
  82. {
  83. if (string.IsNullOrWhiteSpace(key))
  84. {
  85. throw new ArgumentException("Invalid cache key");
  86. }
  87. if (cachePopulate == null)
  88. {
  89. throw new ArgumentException("cachePopulate");
  90. }
  91.  
  92. if (MemoryCache.Default[key]==null)
  93. {
  94. lock (_locker2)
  95. {
  96. if (MemoryCache.Default[key] == null)
  97. {
  98. T cacheValue = cachePopulate();
  99. if (!typeof(T).IsValueType && ((object)cacheValue) == null)
  100. {
  101. return cacheValue;
  102. }
  103. var item = new CacheItem(key, cacheValue);
  104. var policy = CreatePolicy(dependencyFilePath);
  105. MemoryCache.Default.Add(item, policy);
  106. }
  107. }
  108. }
  109.  
  110. return (T)MemoryCache.Default[key];
  111. }
  112.  
  113. /// <summary>
  114. /// 移除指定键的缓存项
  115. /// </summary>
  116. /// <param name="key"></param>
  117. public static void RemoveCacheItem(string key)
  118. {
  119. try
  120. {
  121. MemoryCache.Default.Remove(key);
  122. }
  123. catch (Exception)
  124. {
  125.  
  126. }
  127. }
  128.  
  129. private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
  130. {
  131. var policy = new CacheItemPolicy();
  132. if (slidingExpiration.HasValue)
  133. {
  134. policy.SlidingExpiration = slidingExpiration.Value;
  135. }
  136. else if (absoluteExpiration.HasValue)
  137. {
  138. policy.AbsoluteExpiration = absoluteExpiration.Value;
  139. }
  140.  
  141. policy.Priority = CacheItemPriority.Default;
  142. return policy;
  143. }
  144.  
  145. /// <summary>
  146. /// 缓存文件
  147. /// </summary>
  148. /// <param name="filepath"></param>
  149. /// <returns></returns>
  150. private static CacheItemPolicy CreatePolicy(string filepath)
  151. {
  152. var policy = new CacheItemPolicy();
  153. policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filepath }));
  154.  
  155. policy.Priority = CacheItemPriority.Default;
  156. return policy;
  157. }
  158. }
  159. }

memoryCache的使用的更多相关文章

  1. 【无私分享:ASP.NET CORE 项目实战(第十一章)】Asp.net Core 缓存 MemoryCache 和 Redis

    目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitHub上下载了十几个源码参考, Memory 和 Redis 终于写出一个 ...

  2. 基于MemoryCache的缓存辅助类

    背景: 1. 什么是MemoryCache? memoryCache就是用电脑内存做缓存处理 2.使用范围? 可用于不常变的数据,进行保存在内存中,提高处理效率 代码: /// <summary ...

  3. 从零开始,搭建博客系统MVC5+EF6搭建框架(3),添加Nlog日志、缓存机制(MemoryCache、RedisCache)、创建控制器父类BaseController

    一.回顾系统进度以及本章概要 目前博客系统已经数据库创建.以及依赖注入Autofac集成,接下来就是日志和缓存集成,这里日志用的是Nlog,其实还有其他的日志框架如log4,这些博客园都有很多介绍,这 ...

  4. Android开源框架:Universal-Image-Loader解析(二)MemoryCache

  5. .NET 4.0 MemoryCache with SqlChangeMonitor

    Summary There isn't a lot of documentation on the internet about how to use the SqlChangeMonitor wit ...

  6. 缓存管理Memorycache 的使用

      前言:什么是memoryCache? 一种缓存管理技术,某些只读数据频繁操作数据库,会对系统的性能有很大的开销,所以我们使用缓存技术,当数据库内容更新,我们在更更新缓存的数据值.目前缓存讲技术的产 ...

  7. Asp.net Core 缓存 MemoryCache 和 Redis

    Asp.net Core 缓存 MemoryCache 和 Redis 目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitH ...

  8. 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理(转)

    在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...

  9. 在.NET项目中使用PostSharp,使用MemoryCache实现缓存的处理

    在之前一篇随笔<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>介绍了PostSharp框架的使用,试用PostSharp能给我带来很多便利和优势,减少代码冗余,提高可 ...

  10. .NET Core 2.0迁移技巧之MemoryCache问题修复

    对于传统的.NET Framework项目而言,System.Runtime.Caching命名空间是常用的工具了,其中MemoryCache类则常被用于实现内存缓存. .NET Core 2.0暂时 ...

随机推荐

  1. layui时间控件闪退的问题

    项目上线,发现后台管理系统layui的子页面出现时间控件闪退的问题,根本选取不到时间. 其原因是:如果出现页面找到多个节点,只有第一个节点能正常使用后面的节点都会闪退,可以理解为目前laydate不支 ...

  2. bat批处理文件怎么将路径添加到path环境变量中

    bat批处理文件怎么将路径添加到path环境变量中 摘自:https://zhidao.baidu.com/question/1887763143433391788.html 永久性的: @echo ...

  3. python初级 1 内存和变量

    一.回顾: 1.什么是程序 一堆指令的集合 2.回想一下猜数游戏程序的特征: 1)需要输入(input) 2)会处理输入(process) 3)产生输出(output) 二.程序的一般特征:输入.处理 ...

  4. BDE配置中的一个参数:SHAREDMEMLOCATION

    用Delphi编写数据库程序经常会用到BDE [@more@] 但是前一段发现一个问题,根据程序需要修改了BDE的设置,结果发现只能运行一个实例,再打开这个程序或其他用到BDE的程序系统就会报错: E ...

  5. Swift4.0复习类型定义、类型投射等操作

    1.类型定义: /// 这里将MyInt定义为Int32类型 typealias MyInt = Int32   /// 这里将MyArrayInt定义为[MyInt]数组类型 typealias M ...

  6. Sequelize 类 建立数据库连接 模型定义

    1:Sequelize 类 Sequelize是引用Sequelize模块获取的一个顶级对象,通过这个类可以获取模块内对其他对象的引用.比如utils.Transaction事务类.通过这个顶级对象创 ...

  7. CentOS的开发环境配置(Python、Java、php)

    CentOS安装Python 一.Python源代码编译安装 yum -y install wget yum -y install zlib zlib-devel yum -y install bzi ...

  8. [MySQL]MySQL数据库中如何查询分组后每组中的最后一条记录?

    原文地址:https://codedefault.com/s/how-can-i-retrieve-the-last-record-in-each-group-mysql 问题描述 比如,在MySQL ...

  9. 树莓派3B安装arm64操作系统

    pi64 pi64基于Debian 9,地址如下https://github.com/bamarni/pi64 烧录过程还是用SDFormatter格式化,用Win32DiskImager写入即可,没 ...

  10. python 爬虫实例(二)

    环境: OS:Window10 python:3.7 描述 打开下面的网址,之后抓取其中的图片 https://music.163.com/#/artist/album?id=101988&l ...