Friday, April 23, 2010

The Types of Caching in ASP.NET

Introduction The main benefits of caching are performance-related: operations like accessing database information can be one of the most expensive operations of an ASP page's life cycle. If the database information is fairly static, this database-information can be cached. When information is cached, it stays cached either indefinitely, until some relative time, or until some absolute time. Most commonly, information is cached for a relative time frame. That is, our database information may be fairly static, updated just a few times a week. Therefore, we might want to invalidate the cache every other day, meaning every other day the cached content is rebuilt from the database. Caching in classic ASP was a bit of a chore, it is quite easy in ASP.NET. There are a number of classes in the .NET Framework designed to aid with caching information. In this article, I will explain how .NET supports caching and explain in detail how to properly incorporate each supported method into Web-based applications. Caching Options in ASP.NET ASP.NET supports three types of caching for Web-based applications: Page Level Caching (called Output Caching) Page Fragment Caching (often called Partial-Page Output Caching) Programmatic or Data Caching Output Caching: Caches the output from an entire page and returns it for future requests instead of re-executing the requested page. Fragment Caching: Caches just a part of a page which can then be reused even while other parts of the page are being dynamically generated. Data Caching: Programmatically caches arbitrary objects for later reuse without re-incurring the overhead of creating them. In Detail: Output Caching Output caching is the simplest of the caching options offered by ASP.NET. It is useful when an entire page can be cached as a whole and is analogous to most of the caching solutions that were available under classic ASP. It takes a dynamically generated page and stores the HTML result right before it is sent to the client. Then it reuses this HTML for future requests bypassing the execution of the original code. Telling ASP.NET to cache a page is extremely simple. You simply add the OutputCache directive to the page you wish to cache. The resulting caching is similar to the caching done by browsers and proxy servers, but does have one extremely important difference... you can tell a page which parameters to the page will have an effect on the output and the caching engine will cache separate versions based on the parameters you specify. This is done using the VaryByParam attribute of the OutputCache directive. This is illustrated by a very simple example of output caching. OutputCache Duration="30" VaryByParam="test" This piece of code will cache the result for 30 seconds. During that time, responses for all requests for the page will be served from the cache. Fragment Caching Sometimes it's not possible to cache an entire page. For example, many shopping sites like to greet their users by name. It wouldn't look very good if you went to a site and instead of using your name to greet you it used mine! In the past this often meant that caching wasn't a viable option for these pages. ASP.NET handles this by what they call fragment caching. More often than not, it is impractical to cache entire pages. For example, you may have some content on your page that is fairly static, such as a listing of current inventory, but you may have other information, such as the user's shopping cart, or the current stock price of the company, that you wish to not be cached at all. Since Output Caching caches the HTML of the entire ASP.NET Web page, clearly Output Caching cannot be used for these scenarios: enter Partial-Page Output Caching. Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear in a User Control. One way to specify that the contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content. (Note that for this you should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just inside of the User Control.) Data Caching This is the most powerful of the caching options available in ASP.NET. Using data caching you can programmatically cache anything you want for as long as you want. The caching system exposes itself in a dictionary type format meaning items are stored in name/value pairs. You cache an item under a certain name and then when you request that name you get the item back. It's similar to an array or even a simple variable. In addition to just placing an object into the cache you can set all sorts of properties. The object can be set to expire at a fixed time and date, after a period of inactivity, or when a file or other object in the cache is changed. The main thing to watch out for with data caching is that items you place in the cache are not guaranteed to be there when you want them back. While it does add some work (you always have to check your object exists after you retrieve it), this scavenging really is a good thing. It gives the caching engine the flexibility to dispose of things that aren't being used or dump parts of the cache if the system starts running out of memory. Sometimes, more control over what gets cached is desired. ASP.NET provides this power and flexibility by providing a cache engine. Programmatic or data caching takes advantage of the .NET Runtime cache engine to store any data or object between responses. That is, you can store objects into a cache, similar to the storing of objects in Application scope in classic ASP. (As with classic ASP, do not store open database connections in the cache!) Realize that this data cache is kept in memory and "lives" as long as the host application does. In other words, when the ASP.NET application using data caching is restarted, the cache is destroyed and recreated. Data Caching is almost as easy to use as Output Caching or Fragment caching: you simply interact with it as you would any simple dictionary object. To store a value in the cache, use syntax like this: Cache["Jan"] = bar; // C# To retrieve a value, simply reverse the syntax like this: bar = Cache["Jan"]; // C# Note that after you retrieve a cache value in the above manner you should first verify that the cache value is not null prior to doing something with the data. Since Data Caching uses an in-memory cache, there are times when cache elements may need to be evicted. That is, if there is not enough memory and you attempt to insert something new into the cache, something else has gotta go! The Data Cache engine does all of this scavenging for your behind the scenes, of course. However, don't forget that you should always check to ensure that the cache value is there before using it. This is fairly simply to do - just check to ensure that the value isn't null/Nothing. If it is, then you need to dynamically retrieve the object and restore it into the cache.

No comments:

Post a Comment

Health Benefits of Cashews

  Benefits of Cashews. Healthy food is an integral part of healthy body. Regular exercises such as Yoga and healthy diet is important to...