What is ASP.NET Cache?
For those who are new to the concept, ASP.NET Cache provides a powerful way of storing frequently accessed data rendering your application remarkably fast.
Normally, when a query is executed, data has to be fetched from the database so as to provide the user the requested information. And, a database trip is usually very expensive in terms of performance. This is because of multiple reasons. First, a network trip is involved to the database server. Second, the database server has to compile and execute an SQL query, perform a database I/O operation and then return the results. This specially becomes more visible when you increase the number of transactions.
In order to offset the above mentioned overheads, ASP.NET framework provides an ingenious way of caching frequently needed data close by with the aim of enhancing an application’s performance. Data is stored inside the memory of the application worker process and is extremely fast as compared to a database trip.
Types of ASP.NET Caching
Now let’s discuss the different types of caching available in ASP.NET. To make it possible for programmers to create high end applications, ASP.NET caching comes in two flavors.
The first type helps cache application data inside memory by using a Cache class in the Application scope. With it, programmers can store frequently accessed data inside server memory to avoid having to fetch it again from the database to reproduce it the next time it is needed. Consequently, the application’s speed is dramatically improved.
The second type called Output Cache provides a way to store the output of an ASP.NET page. This allows you to avoid executing that ASP.NET page the next time a user requests it. Instead, the output generated from the last call is returned. This gives your application a considerable performance boost.
1. ASP.NET Application Cache:
ASP.NET provides a Cache class. The Cache instance is created within an Application scope and ends when the application ends. This behavior is termed as being in-process (or in-proc) since the cache resides within the process space of an application. It does have its advantages (which will be discussed in the future posts under this category) as well as its limitations (which will be discussed under the limitations category of this blog).
Using this Cache class, you can perform Add, Insert, Remove, and Get operations. Add lets you store data (any .NET object) by providing a key for it. Similarly, Get lets you fetch data by specifying a key for it. Cache class also provides an automatic data expiration feature that is very useful. Through expirations, you can remove data after a brief interval. This serves two purposes. One, it keeps the data fresh and consistent with the database. And, second, it frees up memory so you can cache other data items.
You can also synchronize your cache with your database by using SqlCacheDependency. It makes sure that if an item changes in the database, it will automatically be removed from cache, helping to keep your cache accurate to a certain extent (more on this in the coming posts).
2. ASP.NET Output Cache:
Output Cache keeps the output of an ASP.NET page in memory so that the next time a user requests that particular page, the page is not even executed and instead its results from the cache are returned to the user. The result is an extremely fast and efficient response. This would be an ideal scenario for pages that make numerous database trips to fetch data but their results do not change on a frequent basis.
Depending on your needs, you can cache entire pages or just portions of a page. Full caching stores all the contents of a particular page which can be later retrieved upon a user request. Partial page caching works in two ways.
2.1 Control caching
Pieces of a page output can be cached by putting the data in a user control and caching that control rather than the whole page. For example if you have a sports page where you have a running commentary, news items and game scores. You may want to put news and game scores (the final scores) sections into cacheable user controls because they do not change but on a daily basis as compared to running commentary that changes by the minute.
2.2 Post-cache substitution
In this type of Output Caching all the page contents are placed inside the cache. Some are static, meaning that they do not change, while others are dynamic for which output is generated dynamically.
ASP.NET Cache Operations:
As a developer, it is of paramount importance that you be able to manipulate cache in a way that helps boost application performance. The three major operations that you can perform with ASP.NET Cache storage are provided below.
1. Adding a data item to ASP.NET Cache
ASP.NET Cache class allows you to use 2 different methods for adding an item to the cache. The first one is the simple Add method while the second is the Insert method. The difference between them is that the Add method returns the object added and if you accidentally add an item that is already present inside the cache, it will not be replaced and it would not cause an exception to be raised.
The Insert method on the other hand has many overloads in order to set dependencies, expirations and removal notifications (a topic that will be discussed in the next post under this category). If you are using this method to add an item to the cache, remember that it will replace any items that exist in the database with the same name.
The following C# code adds a data item to cache by specifying the key and the respective data item.
Customer cust = LoadCustomerFromDatabase(“1000”);
Cache[“Customer:CustomerId:1000”] = cust;
The following C# code adds a data item to cache by specifying the key and the respective data item.
Customer cust = LoadCustomerFromDatabase(“1000”);
Cache.Insert(“Customer:CustomerId:1000”, cust);
2. Retrieving a data item from ASP.NET Cache:
You use the Get method to retrieve data from the cache. In order for you to retrieve anything from the cache, you must have first put it there yourself as described above.
The following C# code retrieves a data item called Customer from cache. It checks for the availability of that item and if it is not found, it loads it from the database and adds it to the Cache.
Customer cust = (Customer) Cache[“Customer:CustomerId:1000”];
if (cust == null)
{
cust = LoadCustomerFromDatabase(“1000”);
Cache.Insert(““Customer:CustomerId:1000″, cust);
}
Notice I have used the Cache.Insert method for adding a data item above. I could have also used the Cache[] technique. Please note that LoadCustomerFromDatabase() is assumed to be a method in your code that knows how to fetch a Customer from the database.
3. Deleting a data item from ASP.NET Cache:
Data inside ASP.NET cacheis not stored indefinitely, it is meant to be temporary. If you want to remove any cached item, you can do so with Cache.Remove().
ASP.NET Cache also provides automatic data removal through expirations and CacheDependency (we will discuss these in the next post under this category).
The following C# code deletes a data item from cache.
Customer cust = (Customer) Cache.Remove(“Customer:CustomerId:1000”);
Here ends this post that outlines ASP.NET Cache intro, its types and how to perform main operations. In the next post we’ll examine how various important ASP.NET Caching features work. If you need more indepth information please visit www.alachisoft.com
Stay in touch to discover more about ASP.NET Cache!!!