How to Use ASP.NET Cache API to Improve Performance
One of the most important aspects of web development is performance. A fast and responsive website can improve user satisfaction, conversion rates, and SEO rankings. One of the ways to achieve better performance is to use caching. Caching is the process of storing frequently used data or resources in memory or on disk, so that they can be accessed faster and reduce the load on the server.
ASP.NET provides a powerful and flexible caching mechanism called the Cache API. The Cache API allows you to store any type of object in the server memory, and control its expiration, dependencies, and priority. You can use the Cache API to cache data from databases, web services, files, or any other source. You can also cache the output of user controls or pages, and vary them by parameters, headers, or cookies.
In this article, we will show you how to use the Cache API to improve the performance of your ASP.NET web applications. We will cover the following topics:
- How to add, retrieve, and remove items from the cache
- How to set expiration policies for cached items
- How to use dependencies to invalidate cached items
- How to use priorities to manage cache memory
- How to cache partial or full page output
How to Add, Retrieve, and Remove Items from the Cache
The Cache API is exposed through the Cache
property of the HttpContext
class. You can access it from any ASP.NET page or user control using the Context.Cache
or simply Cache
shortcut. The Cache
property returns an instance of the System.Web.Caching.Cache
class, which provides methods and properties to manipulate the cache.
To add an item to the cache, you can use the Insert
or Add
methods of the Cache
class. Both methods take the following parameters:
key
: A unique string that identifies the cached itemvalue
: The object to be cacheddependencies
: An optional parameter that specifies the dependencies of the cached item, such as files, keys, or SQL queriesabsoluteExpiration
: An optional parameter that specifies the absolute date and time when the cached item expiresslidingExpiration
: An optional parameter that specifies the relative time interval when the cached item expirespriority
: An optional parameter that specifies the relative priority of the cached itemonRemoveCallback
: An optional parameter that specifies a delegate that is invoked when the cached item is removed
The difference between the Insert
and Add
methods is that the Insert
method will overwrite an existing item with the same key, while the Add
method will return null
if an item with the same key already exists.
Here is an example of how to add an item to the cache using the Insert
method:
// Get some data from a database DataTable dt = GetDataFromDatabase(); // Insert the data into the cache with a key of "MyData" // The data will expire in 10 minutes or if the file "data.xml" changes Cache.Insert("MyData", dt, new CacheDependency(Server.MapPath("data.xml")), DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
To retrieve an item from the cache, you can use the indexer or the Get
method of the Cache
class. Both methods take the key
parameter and return the cached object or null
if the item does not exist. Here is an example of how to retrieve an item from the cache using the indexer:
// Get the data from the cache with a key of "MyData" DataTable dt = Cache["MyData"] as DataTable; // Check if the data is null if (dt == null) { // The data is not in the cache, get it from the database dt = GetDataFromDatabase(); // Insert the data into the cache with the same parameters as before Cache.Insert("MyData", dt, new CacheDependency(Server.MapPath("data.xml")), DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration); } // Use the data for some purpose DoSomethingWithData(dt);
To remove an item from the cache, you can use the Remove
method of the Cache
class. The method takes the key
parameter and returns the removed object or null
if the item does not exist. Here is an example of how to remove an item from the cache using the Remove
method:
// Remove the data from the cache with a key of "MyData" DataTable dt = Cache.Remove("MyData") as DataTable; // Check if the data is not null if (dt != null) { // The data was in the cache, do something with it DoSomethingWithData(dt); }
How to Set Expiration Policies for Cached Items
One of the challenges of caching is to keep the cached data fresh and consistent with the original source. To achieve this, you need to set expiration policies for cached items, so that they are removed from the cache when they become stale or invalid. ASP.NET provides two types of expiration policies: absolute and sliding.
Absolute expiration means that the cached item will expire at a specific date and time, regardless of how often it is accessed. You can set the absolute expiration using the absoluteExpiration
parameter of the Insert
or Add
methods. You can use the DateTime
structure to specify the exact date and time, or use the Cache.NoAbsoluteExpiration
constant to indicate that the item does not expire. Here is an example of how to set an absolute expiration of 10 minutes for a cached item:
// Insert the data into the cache with an absolute expiration of 10 minutes Cache.Insert("MyData", dt, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
Sliding expiration means that the cached item will expire after a certain period of inactivity, that is, if it is not accessed for a specified time interval. You can set the sliding expiration using the slidingExpiration
parameter of the Insert
or Add
methods. You can use the TimeSpan
structure to specify the time interval, or use the Cache.NoSlidingExpiration
constant to indicate that the item does not expire. Here is an example of how to set a sliding expiration of 10 minutes for a cached item:
// Insert the data into the cache with a sliding expiration of 10 minutes Cache.Insert("MyData", dt, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10));
You can also combine absolute and sliding expiration policies for a cached item, but the item will expire when either condition is met. For example, if you set an absolute expiration of 10 minutes and a sliding expiration of 5 minutes, the item will expire after 10 minutes or if it is not accessed for 5 minutes, whichever comes first.
How to Use Dependencies to Invalidate Cached Items
Another way to keep the cached data fresh and consistent with the original source is to use dependencies. Dependencies are objects that represent the sources of the cached data, such as files, keys, or SQL queries. When a dependency changes, the cached item that depends on it is automatically invalidated and removed from the cache.
ASP.NET provides the CacheDependency
class to create dependencies for cached items. The CacheDependency
class has several constructors that take different parameters to specify the type of dependency. You can use the dependencies
parameter of the Insert
or Add
methods to pass a CacheDependency
object to the cache. Here are some examples of how to create and use different types of dependencies:
- File dependency: A file dependency monitors a file or a directory for changes. If the file or any file in the directory is modified, the cached item is invalidated. You can create a file dependency using the
CacheDependency
constructor that takes a file name or an array of file names as a parameter. You can also use theServer.MapPath
method to map a relative path to a physical path. Here is an example of how to create and use a file dependency for a cached item:
// Create a file dependency for the file "data.xml" CacheDependency fileDep = new CacheDependency(Server.MapPath("data.xml")); // Insert the data into the cache with the file dependency Cache.Insert("MyData", dt, fileDep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
Key dependency: A key dependency monitors another cached item for changes. If the other cached item is removed, the dependent item is also invalidated. You can create a key dependency using the CacheDependency
constructor that takes a key name or an array of key names as a parameter. Here is an example of how to create and use a key dependency for a cached item:
// Create a key dependency for the item with the key "MyOtherData" CacheDependency keyDep = new CacheDependency(null, new string[] {"MyOtherData"}); // Insert the data into the cache with the key dependency Cache.Insert("MyData", dt, keyDep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
SQL dependency: A SQL dependency monitors a SQL query for changes. If the result of the query changes, the cached item is invalidated. You can create a SQL dependency using the SqlCacheDependency
class, which inherits from the CacheDependency
class. The SqlCacheDependency
class has several constructors that take different parameters to specify the SQL query and the connection string. You can also use the SqlCacheDependencyAdmin
class to enable and disable SQL dependency for a database or a table.