Export (0) Print
Expand All

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
    
    

Community Additions

ADD
Show:
© 2014 Microsoft