Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Caching in ASP.NET

0.00/5 (No votes)
17 Apr 2002 1  
Demonstrates data caching in ASP.NET

Introduction

ASP.NET has built-in cache engine that is used by ASP.NET pages to store and retrieve objects across HTTP requests. The ASP.NET cache is private to each application and stores objects in memory. The lifetime of the cache is equivalent to the lifetime of the application; that is, when the application is restarted, the cache is recreated.

Placing an item in the cache is done in the following way:

Cache ("key") = Value

Retrieving the data is just as simple:

Value = Cache("key")
If Value <> Null Then
    DisplayData(Value)
End If

For sophisticated functionality in Applications on ASP.NET cache supports scavenging, expiration, and file and key dependencies.

  • Scavenging means that the cache attempts to remove infrequently used or unimportant items if memory becomes scarce.
  • Expiration allows programmers to give cache items lifetimes, which can be explicit (for example, expire at 12:00) or can be relative to an item's last use (for example, expire 10 minutes after the item was last accessed). After an item has expired, it is removed from the cache and future attempts to retrieve it return the null value unless the item is reinserted into the cache.
  • File and key dependencies allow the validity of a cache item to be based on an external file or on another cache item. If a dependency changes, the cache item is invalidated and removed from the cache. For an example of how you might use this functionality, consider the following scenario: an application reads financial information from an XML file that is periodically updated. The application processes the data in the file and creates a graph of objects that represent that data in a consumable format. The application caches that data and inserts a dependency on the file from which the data was read. When the file is updated, the data is removed from the cache and the application can reread it and reinsert the updated copy of the data.

Data Caching Example

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
 
<html>
  <script language="VB" runat="server">
 
    Sub Page_Load(Src As Object, E As EventArgs)
 
        Dim dataSource As DataView
 
        ' Retrieve item from cache if anything is not there then we have to
        ' add to the cache 
        dataSource = Cache("CheDataSet")
 
        If dataSource Is Nothing
 
            Dim Conn As SqlConnection
            Dim Cmd As SqlDataAdapter
 
            Conn = New SqlConnection(_
                           "server=database;uid=sa;pwd=;database=Northwind")
            Cmd = New SqlDataAdapter("select * from customers", Conn)
 
            Dim ds As New DataSet
            Cmd.Fill(ds, "dsUsers")
 
            dataSource = New DataView(ds.Tables("dsUsers"))
            Cache("CheDataSet") = dataSource
 
            CacheMsg.Text = "Dataset was Created directly from the Datebase. " &_
                            "Here the Cache was not used but the Cache was " &_
                            "Created, so check for the performance next time."
        Else
            
            cacheMsg.Text = "Dataset was Retrieved from cache which was " &_
                            "created earlier."
        End If
 
        MyDataGrid.DataSource=dataSource
        MyDataGrid.DataBind()
    End Sub
 
  </script>
 
  <body>
 
    <form method="GET" runat="server">
 
      <h3><font face="Verdana">Caching Data Example</font></h3>
        <i><asp:label id="CacheMsg" runat="server"/></i>
 
      <ASP:DataGrid id="MyDataGrid" runat="server"
        Width="700"
        BackColor="#Eaccff"
        BorderColor="black"
        ShowFooter="false"
        CellPadding=3
        CellSpacing="0"
        Font-Name="Verdana"
        Font-Size="8pt"
       HeaderStyle-BackColor="#ffaad" />
 
      <p>
    </form>
  </body>
</html>

Examples

1. When Executed for the First Time

2. When Executed After the Cache is Created

Conclusion

  1. Data caching should be used very carefully only when required.
  2. Data caching allows objects to be cached programmatically.
  3. The cache is scoped to an application and its lifetime is equivalent to the lifetime of the application.

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here