Compartir a través de


How to: Retrieve Values of Cached Items

To retrieve data from the cache, you specify the key that the cached item was stored under. However, because information stored in the cache is volatile—that is, it might be removed by ASP.NET—the recommended development pattern is to determine first whether the item is in the cache. If it is not, you add it back to the cache and then retrieve the item.

To retrieve the value of a cached item

  • Check to see if the item is not null (Nothing in Visual Basic), in the Cache object. If it exists, assign it to your variable. Otherwise, recreate the item, add it to the cache, and then access it.

    The following code example shows how to retrieve the item named CacheItem from the cache. The code assigns the contents of the item to the variable named cachedString. If the item is not in the cache, the code adds the item to the cache and then assigns the item to cachedString.

    string cachedString;
    cachedString = (string)Cache["CacheItem"];
    if (cachedString == null)
    {
      cachedString = "Hello, World.";
      Cache.Insert("CacheItem", cachedString);
    }
    
    Dim cachedString As String
    cachedString = CStr(Cache("CacheItem"))
    If cachedString Is Nothing Then
      cachedString = "Hello, World."
      Cache.Insert("CacheItem", cachedString)
    End If
    

See Also

Tasks

How to: Add Items to the Cache
How to: Delete Items from the Cache in ASP.NET
How to: Notify an Application When an Item Is Removed from the Cache

Concepts

ASP.NET Caching Overview
Caching Application Data