There are three different techniques you can use to add an item to the Cache object. Depending on the requirements of your application, your choices can range from the simple to the complex.
- You can add items to the cache as you would add items to a dictionary, by specifying the item’s key and value. The following code adds the contents of a text box to the cache.
Cache [ "myText" ] = myTextBox.Value;
Cache ( "myText" ) = myTextBox.Value |
|
C# |
VB |
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.
However, if you want to take advantage of the scavenging, expiration, and dependency support offered by the cache, you must use either the Cache.Insert method or the Cache.Add method. These methods have the same signatures, but the Add method returns an object that represents the cached item.
- The Insert method is overloaded, allowing you to define values for the parameters of the version that you are using. For example, to add only an item key and value, use the following code.
Cache.Insert ( "myData", connectionString );
Cache.Insert ( "myData", connectionString ) |
|
C# |
VB |
- The Add method has the same signature as the Insert method, but returns an object representing the item you added.
Cache.Add ( "myData", connectionString );
Cache.Add ( "myData", connectionString ) |
|
C# |
VB |
Both of these methods offer a great deal of control over the conditions under which the item remains in the cache. Both support making the cached item dependent on external files or directories, other keys within the cache, or arrays of either, as explained in the following section.