SpoiledTechie.com
SpoiledTechie.com

Reputation: 10725

Does ASP.NET Cached Objects update automatically with the object updating?

I found some code on the web and it threw me off. Look at the code below. You will notice only when the Hits == 1, does the cache get added. After that, the cache object isn't updated. It begs the question, does the object when updated, update the cache as well automatically? The answer here would make me remove some code in some of my classes.

public static bool IsValid( ActionTypeEnum actionType )
{
   HttpContext context = HttpContext.Current;
   if( context.Request.Browser.Crawler ) return false;

   string key = actionType.ToString() + context.Request.UserHostAddress;
   var hit = (HitInfo)(context.Cache[key] ?? new HitInfo());

   if( hit.Hits > (int)actionType ) return false;
   else hit.Hits ++;

   if( hit.Hits == 1 )
      context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(DURATION), 
         System.Web.Caching.Cache.NoSlidingExpiration, 
         System.Web.Caching.CacheItemPriority.Normal, null);
   return true;
}

I would only guess that I would need to add the lines after the if statement:

 if( hit.Hits == 1 )
              context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10), 
                 System.Web.Caching.Cache.NoSlidingExpiration, 
                 System.Web.Caching.CacheItemPriority.Normal, null);
    else if (hit.Hits > 1)
{context.Cache.Remove(key);             
 context.Cache.Add(key, hit, null, DateTime.Now.AddMinutes(10), 
                 System.Web.Caching.Cache.NoSlidingExpiration, 
                 System.Web.Caching.CacheItemPriority.Normal, null);
}

Found the code at the bottom of the page here: http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx?msg=2809164

Upvotes: 3

Views: 4058

Answers (1)

womp
womp

Reputation: 116987

This code is updating the cached object regardless of what hits are. The important line is here:

var hit = (HitInfo)(context.Cache[key] ?? new HitInfo());

It's grabbing a reference to the HitInfo object inside the cache, unless it doesn't exist, in which case it creates a new one. So both the ASP.Net Cache and the local variable hit have a reference to the same object - updating it in this code is updating it in the cache.

In the case where it creates a new one, it then adds it to the cache, so the next time the code executes, the line above will be returning that object. There's no need to remove the object and then re-cache it.

Upvotes: 3

Related Questions