DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Writing an Interpreter: Implementation
  • Generics in Java and Their Implementation
  • Simple Sophisticated Object Cache Service Using Azure Redis
  • Scaling Databases With EclipseLink And Redis

Trending

  • The Transformative Power of Artificial Intelligence in Cloud Security
  • On-Call That Doesn’t Suck: A Guide for Data Engineers
  • Filtering Messages With Azure Content Safety and Spring AI
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  1. DZone
  2. Data Engineering
  3. Data
  4. In-memory Cache Implementation in C#

In-memory Cache Implementation in C#

By 
Punit Ganshani user avatar
Punit Ganshani
·
Feb. 02, 12 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
77.3K Views

Join the DZone community and get the full member experience.

Join For Free

The simplest in-memory cache implementation should support

  • Addition of objects into cache either via key-value, or via object creation mechanism
  • Deletion of objects from cache based on key, or object type
  • Querying cache store to check existence of an object

There are several ways to achieve this using multiple design patterns.  But if we were to implement those design patterns in our applications, we would end up designing a framework similar to Enterprise Library Caching block.  So to keep things fairly simple – we need a simple implementation of caching objects in-memory and this cache to be thread-safe for multi-threading applications.

So for that, you can just copy this piece of code into your application and you should be all set with an in-memory cache.

public static class CacheStore

    {

        /// <summary>

        /// In-memory cache dictionary

        /// </summary>

        private static Dictionary<string, object> _cache;

        private static object _sync;





        /// <summary>

        /// Cache initializer

        /// </summary>

        static CacheStore()

        {

            _cache = new Dictionary<string, object>();

            _sync = new object();

        }



        /// <summary>

        /// Check if an object exists in cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        /// <param name="key">Name of key in cache</param>

        /// <returns>True, if yes; False, otherwise</returns>

        public static bool Exists<T>(string key) where T : class

        {

            Type type = typeof(T);

            lock (_sync)

            {

                return _cache.ContainsKey(type.Name + key);

            }

        }



        /// <summary>

        /// Check if an object exists in cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        /// <returns>True, if yes; False, otherwise</returns>

        public static bool Exists<T>() where T : class

        {

            Type type = typeof(T);

            lock (_sync)

            {

                return _cache.ContainsKey(type.Name);

            }

        }



        /// <summary>

        /// Get an object from cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        /// <returns>Object from cache</returns>

        public static T Get<T>() where T : class

        {

            Type type = typeof(T);

            lock (_sync)

            {

                if (_cache.ContainsKey(type.Name) == false)

                    throw new ApplicationException("An object of the desired type does not exist: " + type.Name);



                lock (_sync)

                {

                    return (T)_cache[type.Name];

                }

            }

        }



        /// <summary>

        /// Get an object from cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        /// <param name="key">Name of key in cache</param>

        /// <returns>Object from cache</returns>

        public static T Get<T>(string key) where T : class

        {

            Type type = typeof(T);

            lock (_sync)

            {

                if (_cache.ContainsKey(key + type.Name) == false)

                    throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key));

                lock (_sync)

                {

                    return (T)_cache[key + type.Name];

                }

            }

        }



        /// <summary>

        /// Create default instance of the object and add it in cache

        /// </summary>

        /// <typeparam name="T">Class whose object is to be created</typeparam>

        /// <returns>Object of the class</returns>

        public static T Create<T>(string key, params object[] constructorParameters) where T : class

        {

            Type type = typeof(T);

            T value = (T)Activator.CreateInstance(type, constructorParameters);

            lock (_sync)

            {

                if (_cache.ContainsKey(key + type.Name))

                    throw new ApplicationException(String.Format("An object with key '{0}' already exists", key));

                lock (_sync)

                {

                    _cache.Add(key + type.Name, value);

                }

            }

            return value;

        }



        /// <summary>

        /// Create default instance of the object and add it in cache

        /// </summary>

        /// <typeparam name="T">Class whose object is to be created</typeparam>

        /// <returns>Object of the class</returns>

        public static T Create<T>(params object[] constructorParameters) where T : class

        {

            Type type = typeof(T);

            T value = (T)Activator.CreateInstance(type, constructorParameters);



            lock (_sync)

            {

                if (_cache.ContainsKey(type.Name))

                    throw new ApplicationException(String.Format("An object of type '{0}' already exists", type.Name));

                lock (_sync)

                {

                    _cache.Add(type.Name, value);

                }

            }



            return value;

        }



        public static void Add<T>(string key, T value)

        {

            Type type = typeof(T);



            if (value.GetType() != type)

                throw new ApplicationException(String.Format("The type of value passed to cache {0} does not match the cache type {1} for key {2}", value.GetType().FullName, type.FullName, key));

            lock (_sync)

            {

                if (_cache.ContainsKey(key + type.Name))

                    throw new ApplicationException(String.Format("An object with key '{0}' already exists", key));

                lock (_sync)

                {

                    _cache.Add(key + type.Name, value);

                }

            }

        }



        /// <summary>

        /// Remove an object type from cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        public void Remove<T>()

        {

            Type type = typeof(T);



            lock (_sync)

            {

                if (_cache.ContainsKey(type.Name) == false)

                    throw new ApplicationException(String.Format("An object of type '{0}' does not exists in cache", type.Name));

                lock (_sync)

                {

                    _cache.Remove(type.Name);

                }

            }

        }



        /// <summary>

        /// Remove an object stored with a key from cache

        /// </summary>

        /// <typeparam name="T">Type of object</typeparam>

        /// <param name="key">Key of the object</param>

        public void Remove<T>(string key)

        {

            Type type = typeof(T);



            lock (_sync)

            {

                if (_cache.ContainsKey(key + type.Name) == false)

                    throw new ApplicationException(String.Format("An object with key '{0}' does not exists in cache", key));

                lock (_sync)

                {

                    _cache.Remove(key + type.Name);

                }

            }

        }

    }

Every method has 2 overloads

With Key as a parameter:  This method adds a new key-value in the cache store for a particular object type.  This also means that for a particular object (say Employee), you can have multiple cached-objects (say, multiple employees in an organization)

Without Key as a parameter – This method adds a new key (type of the object) and value in the cache store.  This means, for a particular object type (say ConfigurationSettings) there will single object in the cache (say, configuration value)

Implementation example using CacheStore is:

MonoAssemblyResolver targetAssembly = null;

if (CacheStore.Exists<MonoAssemblyResolver>(projMapping.TargetAssemblyPath))

{

    targetAssembly = CacheStore.Get<MonoAssemblyResolver>(projMapping.TargetAssemblyPath);

}

else

{

    targetAssembly = new MonoAssemblyResolver(projMapping.TargetAssemblyPath);

    CacheStore.Add<MonoAssemblyResolver>(projMapping.TargetAssemblyPath, targetAssembly);

}

Since this uses plain-C# and is light weight, this can be used in ASP.NET MVC, Silverlight, WPF, or Windows Phone applications.  So happy coding!

 

Source: http://www.ganshani.com/2012/01/31/in-memory-cache-implementation-in-c

Cache (computing) Implementation Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Writing an Interpreter: Implementation
  • Generics in Java and Their Implementation
  • Simple Sophisticated Object Cache Service Using Azure Redis
  • Scaling Databases With EclipseLink And Redis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!