首页 > 系统服务 > 详细

System.Runtime.Caching中MemoryCache帮助类

时间:2019-05-09 10:36:43      阅读:229      评论:0      收藏:0      [点我收藏+]

值得参考的几个内存缓存帮助类:

 

参考资料:

https://github.com/Hendy/memory-cache-helper

 

https://gist.github.com/jdalley/0cc8caed02845ad5a6006e4db1267720

 

https://gist.github.com/jwcarroll/4060539

 

https://github.com/khalidsalomao/SimpleHelpers.Net/blob/master/SimpleHelpers/MemoryCache.cs

public static class CacheHelper
{
    private static readonly Object _locker = new object();

    public static T GetCacheItem<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 ArgumentNullException("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)
                {
                    var item = new CacheItem(key, cachePopulate());
                    var policy = CreatePolicy(slidingExpiration, absoluteExpiration);

                    MemoryCache.Default.Add(item, policy);
                }
            }
        }

        return (T)MemoryCache.Default[key];
    }

    private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
    {
        var policy = new CacheItemPolicy();

        if(absoluteExpiration.HasValue)
        {
            policy.AbsoluteExpiration = absoluteExpiration.Value;
        }
        else if(slidingExpiration.HasValue)
        {
            policy.SlidingExpiration = slidingExpiration.Value;
        }

        policy.Priority = CacheItemPriority.Default;

        return policy;
    }
}

System.Runtime.Caching中MemoryCache帮助类

原文:https://www.cnblogs.com/caianhua/p/10836205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!