0

I am creating a web application and am having an issue with my cacheing.

My application has a large amount of data that I want to try and not call from the sql database everytime i need the info.

I have tried to use caching in the following way:

        public static List<DAL.EntityClasses.AccountsEntity> Accounts
    {
        get
        {
            if (HttpContext.Current.Cache["Account"] == null)
            {
                HttpContext.Current.Cache.Insert("Account", LoadAccounts(), null, DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return (List<DAL.EntityClasses.AccountsEntity>)HttpContext.Current.Cache["Account"];
        }
    }

The problem is that it appears that as I am adding items to the Cache, the items that I have already cached get removed.

So most calls are calling the DB to get the data for the cache.

Where have I gone wrong?

Thanks

2 Answers 2

3

This is normal for a LRU cache - least used items get pushed out as the cache fills up capacity.

Configure your cache to larger amounts of data.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Is it an issue if i load a few gigs into the cache, assuming the server is up to the task? I am thinking all the accounts, users, customers, etc. itmes like orders that change i dont want to add.
Not really an issue, if you have the memory for it. Don't cache the whole DB, do cache things that don't change and make sure to set proper expiry times on the cache items.
1

Just FYI: Theres a problem with your implementation of the Accounts property, that is not releated to your original question, but may cause problems in the future:

What could happen is that between this line

if (HttpContext.Current.Cache["Account"] == null)

and this line:

 return (List<DAL.EntityClasses.AccountsEntity>)HttpContext.Current.Cache["Account"]; 

your cache could be cleared / the Account entry could be deleted from the cache.

a better implementation would be:

public static List<DAL.EntityClasses.AccountsEntity> Accounts             
{             
    get             
    {  
      List<DAL.EntityClasses.AccountsEntity> accounts = 
       HttpContext.Current.Cache["Account"] as List<DAL.EntityClasses.AccountsEntity> 

      if(accounts == null)
      {
        accounts = LoadAccounts();
        HttpContext.Current.Cache.Insert("Account", accounts, null, DateTime.Now.AddHours(4), System.Web.Caching.Cache.NoSlidingExpiration);          
      }  
      return accounts;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.