In addition to the ability to output cache multiple versions of entire pages and user controls, ASP.NET includes a full-featured cache engine that can be used by an application to store arbitrary objects in memory, which can then be retrieved by the same or any other page that is part of the application.
This caching mechanism is implemented via the Cache class, an instance of which exists for each application configured on a Web server.
The ASP.NET cache is private to each Web application, and its lifetime depends on the start and end of any given application. This means that only pages within an application domain can have access to its cache. When the application starts, an instance of the application’s Cache object is created. When the application ends, its cache is cleared.
The application cache provides a simple dictionary interface using key=value
pairs that allow programmers to easily store and retrieve objects from the cache. In the simplest case, placing an item in the cache is just like adding an item to a dictionary:
Cache [ "mykey" ] = myValue;
Cache ( "mykey" ) = myValue
Cache ( "mykey" ) = myValue;
|
|
C# |
VB |
JScript |
Retrieving the data is just as simple:
myValue = Cache [ "mykey" ];
if ( myValue != null ) {
DisplayData ( myValue );
}
myValue = Cache ( "mykey" )
If myValue <> Null Then
DisplayData ( myValue )
End If
myValue = Cache ( "mykey" );
if ( myValue != null ) {
DisplayData ( myValue );
}
|
|
C# |
VB |
JScript |
The following example shows a simple use of the cache. When first requested, the page executes a database query and caches the result, which it continues to use for the lifetime of the application. The initial message on the page indicates that the data was explicitly retrieved from the database server. Thereafter, the cached version is used.
For relevant information, see Adding Items to the Cache and Retrieving Values of Cached Items.