1 借鉴这篇文章

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Caching;
using System.Diagnostics; namespace ConsoleApp1
{
public static class MemoryCacheHelper
{
private static readonly object _locker = new object();
private static readonly object _locker2 = new object(); /// <summary>
/// 根据key取缓存,不存在则返回null
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public static T GetCacheItem<T>(String key)
{
try
{
return (T)MemoryCache.Default[key];
}
catch (Exception ex)
{ return default(T);
}
} /// <summary>
/// 是否包含指定键的缓存项
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Contains(string key)
{
return MemoryCache.Default.Contains(key);
} public static T GetOrAddCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Invalid cache key");
}
if (cachePopulate == null)
{
throw new ArgumentException("cachePopulate");
}
if (slidingExpiration == null && absoluteExpiration == null)
{
throw new ArgumentException("Either a sliding expiration or absolute must be provided");
}
if (MemoryCache.Default[key] == null)
{
lock (_locker)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null)
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
MemoryCache.Default.Add(item, policy);
} }
} return (T)MemoryCache.Default[key];
} public static T GetOrAddCacheItem<T>(string key,Func<T> cachePopulate,string dependencyFilePath)
{
if (string.IsNullOrWhiteSpace(key))
{
throw new ArgumentException("Invalid cache key");
}
if (cachePopulate == null)
{
throw new ArgumentException("cachePopulate");
} if (MemoryCache.Default[key]==null)
{
lock (_locker2)
{
if (MemoryCache.Default[key] == null)
{
T cacheValue = cachePopulate();
if (!typeof(T).IsValueType && ((object)cacheValue) == null)
{
return cacheValue;
}
var item = new CacheItem(key, cacheValue);
var policy = CreatePolicy(dependencyFilePath);
MemoryCache.Default.Add(item, policy);
}
}
} return (T)MemoryCache.Default[key];
} /// <summary>
/// 移除指定键的缓存项
/// </summary>
/// <param name="key"></param>
public static void RemoveCacheItem(string key)
{
try
{
MemoryCache.Default.Remove(key);
}
catch (Exception)
{ }
} private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
{
var policy = new CacheItemPolicy();
if (slidingExpiration.HasValue)
{
policy.SlidingExpiration = slidingExpiration.Value;
}
else if (absoluteExpiration.HasValue)
{
policy.AbsoluteExpiration = absoluteExpiration.Value;
} policy.Priority = CacheItemPriority.Default;
return policy;
} /// <summary>
/// 缓存文件
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
private static CacheItemPolicy CreatePolicy(string filepath)
{
var policy = new CacheItemPolicy();
policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string>() { filepath })); policy.Priority = CacheItemPriority.Default;
return policy;
}
}
}

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. 在gitlab新建分支,IDEA切换时找不到的解决办法

    VCS——>Git——>Fetch

  2. asp乱码问题

    UTF-8编码的话:在ASP脚本顶部加入<%@Language="vbscript" Codepage="65001"%>以及再在<head& ...

  3. Spring的@ExceptionHandler和@ControllerAdvice统一处理异常

    之前敲代码的时候,避免不了各种try..catch, 如果业务复杂一点, 就会发现全都是try…catch try{ ..........}catch(Exception1 e){ ......... ...

  4. linux记录-安装elk记录(参考博文)

    什么是ELK? 通俗来讲,ELK是由Elasticsearch.Logstash.Kibana .filebeat三个开源软件的组成的一个组合体,这三个软件当中,每个软件用于完成不同的功能,ELK 又 ...

  5. Python - Django - ORM 常用的字段属性

    字段参数: null:用于表示某个字段可以为空 unique:如果设置为 unique=True,则该字段在此表中必须是唯一的 db_index:如果 db_index=True,则代表着为此字段设置 ...

  6. git切换到某个tag, 从tag切换回当前分支

    git clone 整个仓库后使用,以下命令就可以取得该 tag 对应的代码了 git checkout tag_name 但是,这时候 git 可能会提示你当前处于一个“detached HEAD& ...

  7. 【JS新手教程】LODOP打印复选框选中的任务或页数

    之前的博文:[JS新手教程]LODOP打印复选框选中的内容关于任务:Lodop打印语句最基本结构介绍(什么是一个任务)关于本文用到的JS的eval方法:JS-JAVASCRIPT的eval()方法该文 ...

  8. HTML布局排版2 div的和图片平铺方便管理

    在HTML里,由于浏览器显示器等差异,浏览器的宽度也会有变化,为了适应不同的宽度,需要用到平铺.例如页面前面的固定的条等,如果是纯色,可以用背景色,如果不是纯色,是渐变等,可以用条状图平铺.常见的布局 ...

  9. 获取两日期之前集合并转为String类型的集合

    /** * 获取两个日期之间的日期 * * @param start 开始日期 * @param end 结束日期 * @return 日期集合 */ private static List<D ...

  10. jmeter的安装教程

    JMETER安装教程 jmeter的安装教程 1:安装jdk并且配置好环境变量,此处就不做赘述(前面的文档中有) 2:下载jmeter文件和jmeter的插件文件 JMeter:http://jmet ...