Click here to Skip to main content
15,886,067 members
Articles / Programming Languages / C#
Tip/Trick

Simple cache object and cache dictionary

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Jun 2012CPOL2 min read 18K   392   4   2
No need for complex settings, just create an object or a dictionary and let the helpers handle the cache.

Introduction

I had to use something that is commonly used: caching different types of objects. To my surprise, there are lots of solutions out there, but all are very complicated, and because they are designed to handle a wide range of needs, it is required to define quite a few settings before using them.

In this solution my aim was to do it as simple as possible with minimum pre-settings to meet my goals.

Background

I created two very simple classes designed to help create a cache object and a cache dictionary.

When creating the objects (in the constructor) we define the source data for getting the objects. When we need to use the value, the cache object will check if the object is in the cache and if not it will call the Fill method.

Using the code

When we call:

C#
var userName = _userName.Value;

CacheObject checks in the internal System.Runtime.Caching.MemoryCache object if the value exists: 

C#
var cacheValue = _cache[string.Empty];

(string.Empty is just a dummy value.)

If the value is not in the cache, we will call:

C#
cacheValue = _getValueFunc.Invoke();

We need to define the function getValueFunc in the CacheObject constructor. In this function we can call the service or a value resource.

In the constructor, we can also define the expiration time for the Cache object – after the expiration time is complete, CacheObject will call the getValueFunc again.

CacheDictionary is based on the same logic but the main difference is that in the constructor, we need to define a function that gets the key parameter of the dictionary and returns the value of the dictionary.

When the expiration is not defined in the constructor, CacheObject will take the default expiration value from the Properties.Settings.Default.DefaultCasheTimeoutSeconds value. So we can set this value in the config file for all applications.

Enjoy.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer Consist Systems
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI like it Pin
FatCatProgrammer5-Jun-12 6:02
FatCatProgrammer5-Jun-12 6:02 
Questionhi Pin
beleshi3-Jun-12 23:31
beleshi3-Jun-12 23:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.