asp.net.ph

Skip Navigation LinksASP.NET Applications > ASP.NET Optimization > ASP.NET Caching Features > Caching Application Data > Adding Items to the Cache

Adding Items to the Cache

ASP.NET Web Applications   ASP .NET Caching Features   Caching Application Data


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.

To add an item to the cache specifying its key and value

  • 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;
  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.

Using the Data Cache
Run Sample | View Source

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.

To add items to the cache using the Insert method

  • 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 );
  C# VB

To add items to the cache using the Add method

  • The Add method has the same signature as the Insert method, but returns an object representing the item you added.

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.

More ...
Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note