C#.NET WINFORM 缓存 System.Runtime.Caching MemoryCache

发布时间 2023-08-18 13:34:29作者: runliuv

C#.NET WINFORM 缓存 System.Runtime.Caching MemoryCache

 

工具类:

using System;
using System.Runtime.Caching;

namespace CommonUtils
{
    /// <summary>
    /// 基于MemoryCache的缓存辅助类
    /// </summary>
    public static class MemoryCacheHelper
    {

        public static void SetCache<T>(string key, T cacheItem, TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null)
        {
            if (String.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Invalid cache key");
            }
            if (cacheItem == null)
            {
                throw new ArgumentNullException("cacheItem null ");
            }
            if (slidingExpiration == null && absoluteExpiration == null)
            {
                throw new ArgumentException("Either a sliding expiration or absolute must be provided");
            }
            MemoryCache.Default.Remove(key);

            var item = new CacheItem(key, cacheItem);
            var policy = CreatePolicy(slidingExpiration, absoluteExpiration);
            MemoryCache.Default.Add(item, policy);
        }

        public static T GetCache<T>(string key)
        {
            if (String.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Invalid cache key");
            }
            return (T)MemoryCache.Default[key];
        }

        /// <summary>
        /// 移除缓存
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveCache(string key)
        {
            MemoryCache.Default.Remove(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;
        }
    }
}

使用:

string cacheKey = "person_key";
                MemoryCacheHelper.SetCache<Person>(cacheKey,
                   new Person() { Id = Guid.NewGuid(), Name = "wolfy" }
                   , new TimeSpan(0, 30, 0));

                Console.WriteLine("获取缓存中数据");
                Person p2 = MemoryCacheHelper.GetCache<Person>(cacheKey);
                if (p2 != null)
                {
                    Console.WriteLine(p2.ToString());
                }
                MemoryCacheHelper.RemoveCache(cacheKey);
                Person p3 = MemoryCacheHelper.GetCache<Person>(cacheKey);
                if (p3 != null)
                {
                    Console.WriteLine(p3.ToString());
                }
                Console.Read();

--