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         }

      

  • 相关阅读:
    Shared Memory in Windows NT
    Layered Memory Management in Win32
    软件项目管理的75条建议
    Load pdbs when you need it
    Stray pointer 野指针
    About the Rebase and Bind operation in the production of software
    About "Serious Error: No RTTI Data"
    Realizing 4 GB of Address Space[MSDN]
    [bbk4397] 第1集 第一章 AMS介绍
    [bbk3204] 第67集 Chapter 17Monitoring and Detecting Lock Contention(00)
  • 原文地址:https://www.cnblogs.com/NoRoad/p/6256046.html
Copyright © 2011-2022 走看看