zoukankan      html  css  js  c++  java
  • 基于MemoryCache的缓存辅助类

    背景:

      1. 什么是MemoryCache?

        memoryCache就是用电脑内存做缓存处理

      2.使用范围?

        可用于不常变的数据,进行保存在内存中,提高处理效率

    代码:

     1         /// <summary>
     2         /// 基于MemoryCache的缓存辅助类
     3         /// </summary>
     4         public static class MemoryCacheHelper
     5         {
     6             private static readonly Object _locker = new object();
     7 
     8             public static T GetCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
     9             {
    10                 if (String.IsNullOrWhiteSpace(key)) throw new ArgumentException("Invalid cache key");
    11                 if (cachePopulate == null) throw new ArgumentNullException("cachePopulate");
    12                 if (slidingExpiration == null && absoluteExpiration == null) throw new ArgumentException("Either a sliding expiration or absolute must be provided");
    13 
    14                 if (MemoryCache.Default[key] == null)
    15                 {
    16                     lock (_locker)
    17                     {
    18                         if (MemoryCache.Default[key] == null)
    19                         {
    20                             var item = new CacheItem(key, cachePopulate());
    21                             var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
    22 
    23                             MemoryCache.Default.Add(item, policy);
    24                         }
    25                     }
    26                 }
    27 
    28                 return (T)MemoryCache.Default[key];
    29             }
    30 
    31             private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
    32             {
    33                 var policy = new CacheItemPolicy();
    34 
    35                 if (absoluteExpiration.HasValue)
    36                 {
    37                     policy.AbsoluteExpiration = absoluteExpiration.Value;
    38                 }
    39                 else if (slidingExpiration.HasValue)
    40                 {
    41                     policy.SlidingExpiration = slidingExpiration.Value;
    42                 }
    43 
    44                 policy.Priority = CacheItemPriority.Default;
    45 
    46                 return policy;
    47             }
    48         }

      

  • 相关阅读:
    asp:时间的计算
    彻底理解position与anchorPoint
    关于写代码的一些心得总结2014-12-28 23:49:39
    C#如何将线程中的代码抛到主线程去执行
    pac 文件使用到的javascript函数
    webview改变网页宽度
    iOS按钮长按
    ios 页面滑入滑出
    UILable自适应frame
    制作静态库文件(.a文件)
  • 原文地址:https://www.cnblogs.com/NoRoad/p/6256046.html
Copyright © 2011-2022 走看看