Click here to Skip to main content
15,879,095 members
Articles / Web Development / ASP.NET

Caching in ASP.NET

Rate me:
Please Sign up or sign in to vote.
2.86/5 (36 votes)
17 Apr 20022 min read 159.2K   1.8K   53   14
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:

VB
Cache ("key") = Value

Retrieving the data is just as simple:

VB
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

VB
<%@ 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

Image 1

2. When Executed After the Cache is Created

Image 2

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.


Written By
Web Developer
India India
I am working on .Net Techlology Extensively. I am presently in Bangalore.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ali Al Omairi(Abu AlHassan)13-Feb-11 0:06
professionalAli Al Omairi(Abu AlHassan)13-Feb-11 0:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.