Bhawna Jain
Bhawna Jain

Reputation: 759

Caching in C# to improve performance[ASP.Net MVC]

I have a function in controller which returns a list of countries.I am trying to implement caching in it..so that list is fetched only when empty at server side.I found two ways:

  1. Using OutputCache

     [OutputCache(Duration = 86400, Location = OutputCacheLocation.Server,VaryByParam ="none")]
     public function getelement(){
     //return list of country;
     }
    

But I am not able to test it maybe because both client and server is myself in this.

  1. Using MemoryCache

     private static MemoryCache _cache = MemoryCache.Default;
    
    _cache.Add(cacheKey, obj, policy);//MemoryCache(String, NameValueCollection, Boolean)
    

I am not able to correctly implement 2nd one.

Any suggestions?

Update 1:

   ObjectCache cache = MemoryCache.Default;
            string cacheKey = "countrylist";
            var cacheObject = cache.Get(cacheKey);

            if (cacheObject == null)
            {
                cacheObject = getelement();//returns a list of string type
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60);
                cache.Add(cacheKey, cacheObject, policy);

            }    

I am not able to use cacheObject or access the list which now is of object type.

I tried following solutions:

1. var mylist = (from p in cacheObject.Cast<string>(IQueryable) select p).ToList();


2. List<string> mylist = cacheObject.AsQueryable().Cast<string>().Select(values).ToList();
 values.AddRange(mylist);

But I am not able to create a list of string type :(

Upvotes: 0

Views: 538

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

MemoryCache.Default is already static, there is no need to store it again.

You can implement similar to this:

ObjectCache cache = MemoryCache.Default;
var cacheObject = cache.Get(cacheKey);

if (cacheObject == null)
{
    cacheObject = //do something to get it
    CacheItemPolicy policy = new CacheItemPolicy();
    policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(2);
    cache.Add(cacheKey, cacheObject, policy);
}
return cacheObject;

Update

To @mjwills point, if you have a web farm/load balanced site each server will hold it's own cache and they could be out of sync (for at least the duration of the expiration) between servers. You might be OK with this, or you might not. If not consider NCache, Redis, or similar product.

Upvotes: 1

Related Questions