ASP.NET WP - Caching


Advertisements

When someone requests a page from your site, then the web server has to do some work in order to fulfill the request. So the server might have to perform tasks which will take a long time, such as retrieving data from a database.

  • In some cases, if your site experiences a lot of traffic, a whole series of individual requests that cause the web server to perform the complicated or slow task can add up to a lot of work.

  • This can ultimately affect the performance of the site.

  • One way to improve the performance of your website is to cache data.

  • When your site gets repeated requests for the same information, and the information does not need to be modified for each person, and it's not time sensitive, so instead of re-fetching or recalculating it, you can fetch the data once and then store the results.

  • The next time a request comes in for that information, you just get it out of the cache.

How to Cache the Data?

Let’s have a look into a simple example in which we will cache the data when the page is first time loaded. So let’s create a new CSHTML file with WebCache.cshtml name, and replace the following code.

@{
   var cacheItemKey = "CachedTime";
   var cacheHit = true;
   var time = WebCache.Get(cacheItemKey);
   
   if (time == null){
      cacheHit = false;
   }
   
   if (cacheHit == false){
      time = @DateTime.Now;
      WebCache.Set(cacheItemKey, time, 1, false);
   }
}

<!DOCTYPE html>
<html>
   
   <head>
      <title>WebCache Helper Sample</title>
   </head>
   
   <body>
      <div>
         @if (cacheHit){
            @:Found the time data in the cache.
         } else {
            @:Did not find the time data in the cache.
         }
      </div>
      
      <div>
         This page was cached at @time.
      </div>
   
   </body>
</html>
  • As you can see in the above code, when we cache the data, we will put it into the cache using a name this is unique across the website. In this case, we will use a cache entry named CachedTime. This is the cacheItemKey.

  • The code first reads the CachedTime cache entry. If a value is returned, the code just sets the value of the time variable to the cache data.

  • But if the cache entry doesn't exist the code sets the time value, adds it to the cache, and sets an expiration value to one minute.

  • The WebCache.Set(cacheItemKey, time, 1, false) shows how to add the current time value to the cache and set its expiration to 1 minute.

Let’s run the application and specify the following url − http://localhost:50180/WebCache.cshtml and you will see the following page.

Web Cache

Now let’s refresh your page within a minute and you will see the same time, this is because the time is loaded from the cache.

WebCache Helper
Advertisements