OBJECT CACHING - .NET 4

这篇文章,主要讲在.NET中的Cache

原文地址:OBJECT CACHING - .NET 4



As a developer, we need to use all the tools atour disposal(at one’s diposal供任意使用,可自行支配) to develop faster and more robustapplications. One of the ways we can achieve this is by using caching. Caching is the process of storing frequently used data on theserver to fulfil subsequent requests. Now there are a few differenttypes of caching available to the .NET developer, but inthis article I am going to discuss data caching using the object cache.The cache object enables you to store everything from simple name / value pairsto more complex objects such as datasets and entire pages.作为一名程序开发人员,我们的目标是开发faster and more robust(快捷且健壮的)应用程序。其中一个方法,就是使用Caching。而实现Caching也有许多不同的方法,本文介绍的是the object cache.

 

Previously, the cache object used to fall under the System.Web.Caching.Cache namespace.Due to it's power and awesomeness, many developers would copy this namespaceinto their projects and use it in other applications such as Windows Forms andWPF apps. With the release of .NET 4, the namespace has beenrefactored and totally rebuilt into the new namespace of System.Runtime.Caching. The old namespace is still available, but anynew enhancements will be added to the System.Runtime.Caching namespace.命名空间的变迁


(1)首先,添加“引用”

To start, you add a reference to the System.Runtime.Caching object in your project.

OBJECT CACHING - .NET 4_第1张图片


If you wanted to add an item to the cache, you would need to do the following:

        public static void AddItem(object objectToCache, string key)
        {
            ObjectCache cache = MemoryCache.Default;
            cache.Add(key,objectToCache,DateTime.Now.AddDays(30));
        }

In this line, we are obtaining a reference to the default MemoryCache instance. Using the new .NET Caching runtime, you can have multiple MemoryCaches inside a single application.

ObjectCache Cache = MemoryCache.Default;

Then we add the object to the cache along with a key. The key allows us to retrieve this at a later point.

Sometimes you might come across a scenario where a similar object will have similar name, in this case you might want to build a dynamic key string to identify your objects.

Cache.Add("Key", objectToCache, DateTime.Now.AddDays(30));

Retrieving our object is just as simple, but this time let's make a re-usable method that is a lot sexier.


        static readonly ObjectCache Cache = MemoryCache.Default;

        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <returns>Cached item as type</returns>
        public static T Get<T>(string key) where T:class
        {
            
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }


NOTE: If you make changes on your application, you might not see them immediately because they might be in cache. You might need to remove the object in order to see your changes - you can always add them back in!

    public class CacheLayer
    {
        static readonly ObjectCache Cache = MemoryCache.Default;

        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <returns>Cached item as type</returns>
        public static T Get<T>(string key) where T : class
        {
            try
            {
                return (T)Cache[key];
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="objectToCache">Item to be cached</param>
        /// <param name="key">Name of item</param>
        public static void Add<T>(T objectToCache, string key) where T : class
        {
            Cache.Add(key, objectToCache, DateTime.Now.AddDays(30));
        }

        /// <summary>
        /// Insert value into the cache using
        /// appropriate name/value pairs
        /// </summary>
        /// <param name="objectToCache">Item to be cached</param>
        /// <param name="key">Name of item</param>
        public static void Add(object objectToCache, string key)
        {
            Cache.Add(key, objectToCache, DateTime.Now.AddDays(30));
        }

        /// <summary>
        /// Remove item from cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        public static void Clear(string key)
        {
            Cache.Remove(key);
        }

        /// <summary>
        /// Check for item in cache
        /// </summary>
        /// <param name="key">Name of cached item</param>
        /// <returns></returns>
        public static bool Exists(string key)
        {
            return Cache.Get(key) != null;
        }

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




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