c# - 对象缓存 OBJECT CACHING

对象缓存类,转自此人博客:http://deanhume.com/Home/BlogPost/object-caching----net-4/37

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace YourNameSpace
{
    /// 
    /// This class was borrowed from
    /// http://deanhume.com/Home/BlogPost/object-caching----net-4/37
    /// 
    public class CacheLayer
    {
        static readonly ObjectCache Cache = MemoryCache.Default;

        /// 
        /// Retrieve cached item
        /// 
        /// Type of cached item
        /// Name of cached item
        /// Cached item as type
        public static T Get(string key) where T : class
        {
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }

        /// 
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// 
        /// Type of cached item
        /// Item to be cached
        /// Name of item
        public static void Add(T objectToCache, string key) where T : class
        {
            Cache.Add(key, objectToCache, MemoryCache.InfiniteAbsoluteExpiration);
        }

        /// 
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// 
        /// Item to be cached
        /// Name of item
        public static void Add(object objectToCache, string key)
        {
            Cache.Add(key, objectToCache, MemoryCache.InfiniteAbsoluteExpiration);
        }

        /// 
        /// Remove item from cache
        /// 
        /// Name of cached item
        public static void Clear(string key)
        {
            Cache.Remove(key);
        }

        /// 
        /// Check for item in cache
        /// 
        /// Name of cached item
        /// 
        public static bool Exists(string key)
        {
            return Cache.Get(key) != null;
        }

        /// 
        /// Gets all cached items as a list by their key.
        /// 
        /// 
        public static List GetAll()
        {
            return Cache.Select(keyValuePair => keyValuePair.Key).ToList();
        }
    }
}

你可能感兴趣的:(C#)