SetiSeeker
SetiSeeker

Reputation: 6684

ASP.net Cacheing - Proper Usage

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

Upvotes: 0

Views: 211

Answers (2)

Andre Kraemer
Andre Kraemer

Reputation: 2761

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;
   }
}

Upvotes: 1

Oded
Oded

Reputation: 499002

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.

Upvotes: 3

Related Questions