22 Jun

C# Generic Cache Manager Example

This examples shows how to implement a generic cache manager class in C#. We often need to cache to the some objects in our programs, ecpecially for objects that frequently access. Following sample is implemented for this purpose.

Usage:


            CacheManager<string> cm = new CacheManager<string>(); //keep this instance in a class

            cm.Add("key1", "data1", 5000);  //remove after 5 sc
            cm.Add("key2", "data2");        //don't remove from cache
            cm.Add("key3", "data3", 3000);  //remove after 3 sc
            cm.Add("key4", "data4");        //don't remove from cache

Also if we want to use only one cache manager instance, we can use Singleton Pattern in Design Patterns.

For more information about Singleton Pattern:
https://csharpexamples.com/c-multithread-singleton-pattern-example

Generic Cache Manager Class:


    public class CacheManager<T>
    {
        private Dictionary<string, T> _items = null;
        public CacheManager()
        {
            _items = new Dictionary<string, T>();
        }

        private void TimerProc(object state)
        {
            //Remove the cached object
            string key = state.ToString();
            this.Remove(key);
        }

        public void Add(string key, T obj, int cacheTime = System.Threading.Timeout.Infinite)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");

            if (_items.Keys.Contains(key))
                throw new ArgumentException("An element with the same key already exists.");

            //Set timer
            System.Threading.Timer t = new System.Threading.Timer(new TimerCallback(TimerProc), 
                                                                 key, 
                                                                 cacheTime, 
                                                                 System.Threading.Timeout.Infinite);

            _items.Add(key, obj);
        }
        
        public bool Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");
            
            return _items.Remove(key);
        }

        public T Get(string key)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key is null.");

            if (!_items.Keys.Contains(key))
                throw new KeyNotFoundException("key does not exist in the collection.");

            return _items[key];
        }

        public void Clear()
        {
            _items.Clear();
        }
    }

2 thoughts on “C# Generic Cache Manager Example

Leave a Reply

Your email address will not be published. Required fields are marked *