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. openresty开发系列14--lua基础语法3函数

    openresty开发系列14--lua基础语法3函数 一)function (函数) 有名函数: optional_function_scope function function_name( ar ...

  2. mtcnn论文学习

    Joint Face Detection and Alignment using Multi-task Cascaded Convolutional Networks 使用多任务级联卷积网络连接人脸检 ...

  3. 关于haproxy的一些属性和acl 规则

    首先是haproxy.cfg文件的基本标注 当然实际配件没有下面这个复杂,可以根据需要自行增减. global log 127.0.0.1 local1 maxconn 65000 #最大连接数 ch ...

  4. Linux脚本检测当前用户是否为root用户

    #/bin/bash if [ $UID -ne 0 ]; then echo Non root user. Please run as root. else echo Root user fi

  5. docker 下mysql 和postgresql 数据库的搭建以及数据文件的迁移和备份

    service docker start - docker 启动 service docker stop - docker 关闭 1.docker 镜像创建—使用的默认镜像有数据卷 docker pu ...

  6. linux系统 重启盘符错乱问题

    linux磁盘重启乱序问题处理 最近到客户那去巡检时,客户提到一个问题,他们的rac在重启的时候,原来的sda1.sdb1.sdc1会对应变成sdd1.sde1.sdf1,由于他们使用的是盘符来绑定裸 ...

  7. 由于我最近搞了个wordpress搭建博客,这里我为大家分享一哈,使用wordpress过程中遇到的坑

    Windows server下搭建mysql+php+apache环境参考教程: https://blog.csdn.net/qq_38125058/article/details/81157865 ...

  8. 第八章 跨语言服务治理方案 Service Mesh

    8.1 Service Mesh 概述 新兴的下一代微服务架构,被称为下一代微服务,同时也是云原生技术栈的代表技术之一. 8.1.1 Service Mesh的由来 从2016年到2018年,serv ...

  9. 032 Android智能下拉刷新框架-SmartRefreshLayout+RecyclerView的使用

    1.SmartRefreshLayout介绍 SmartRefreshLayout的目标是打造一个强大,稳定,成熟的下拉刷新框架,并集成各种的炫酷.多样.实用.美观的Header和Footer. 正如 ...

  10. [转帖]时序数据库技术体系 – InfluxDB TSM存储引擎之数据读取

    时序数据库技术体系 – InfluxDB TSM存储引擎之数据读取 http://hbasefly.com/2018/05/02/timeseries-database-7/  2018年5月2日   ...