Use caching in ASP.NET Web Pages

Artikeln finns på svenska här:
http://www.aspsidan.se/default.asp?page=readarticle&artId=709 

Web sites are often complex and show much information from external sources. News on the site can come from the database, news from other sites are aggregated from their RSS feed, stock quotes can be imported using a web service and so on. Since all these calls can take some time to do, the result can be a slow web site. To solve this you can cache the information on the page, which saves the information in the memory so you only need to get this information when it´s updated. If we set the cache to 20 minutes, the data will be saved for 20 minutes in the memory, and will after that be imported again.

In ASP.NET Web Pages there is a helper which makes it possible to fast and easy use the cache in .NET.

These are the methods that can be used:

  • WebCache.Get(string key)
    • Returns the value with the key specified.
  • WebCache.Set(string key, object value[, int minutesToCache][bool slidingExpiration]
    • Inserts data in the cache with the specified key. The optional parameters minutesToCache and slidingExpiration determines how long the value should be cached, and if its expiration will be extended when used.
  • WebCache.Remove(string key)
    • Removes the object with the specified key from the cache.

What we are going to do now is to see if there is a date in the cache. If it is there we print it out, and if not we save the date in the cache and print it out. We are also adding a button which we can click on to remove the cached value.

The full code for the page:

@{
    if (IsPost)
    {
        WebCache.Remove("date");
    }
 
    DateTime date = DateTime.Now;
    DateTime cachedDate = DateTime.Now;
 
    if (WebCache.Get("date") != null)
    {
        cachedDate = WebCache.Get("date").ToString().AsDateTime();
    }
    else
    {
        WebCache.Set("date", date, 3);
    }
}
 
<!DOCTYPE html>
<html>
    <head>
        <title>ASP.NET Web Pages Cache</title>
    </head>
    <body>
        <p>
            Cached time: @cachedDate.ToLongTimeString()
        </p>
        <p>
            Current time: @date.ToLongTimeString()
        </p>
        <p>
            <form action="/Cache" method="post">
                <input type="submit" value="Remove from cache" />
            </form>
        </p>
    </body>
</html>

The first thing we do here is to check whether the user have posted to the page or not, which we have not the first time we visit the page. After that we create two variables, one with the current time, and one with the cached time, which is the same as the current the first time we visit the page.

The next step is to see if there is anything saved in the cache. We get the value for the key ”date” and check if it is null. If the value exists, we save it as a DateTime object using the extension method AsDateTme(), which can be used by all string objects in ASP.NET Web Pages. If the value is not yet in the cache, we save the value there for three minutes.

When all the code have been executed we will have two values – the current time and the cached time. On the page we are going to print both values which are the same for the first time, and when we update the page the cached value will be the same as before and the other value will be updated.

The cached value will be updated after three minutes, or when we click on the button which will remove it from the cache.

Except for simple types like DateTime we can save more complex type, like a list with news on the page.

It is important to remember to not cache everything too long. Information that needs to be updated often can be cached for a short time (like a chat), while things that do not have to be updated often can be cached for a longer time (news and similar).

The article can be found as pdf and xps here:
http://www.aspsidan.se/default.asp?page=readarticle&artId=709

3 Comments

Comments have been disabled for this content.