Library tutorials & articles

.NET Data Caching

Introduction

In simple terms data caching is storing data in memory for quick access. Typically information that is costly to obtain (in terms of performance) is stored in the cache. One of the more common items stored in a cache in a Web application environment is commonly displayed database values; by caching such information, rather than relying on repeated database calls, the demand on the Web server and database server's system resources are decreased and the Web application's scalability increased. As Microsoft eloquently puts it, "Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In the context of a Web application, caching is used to retain pages or data across HTTP requests and reuse them without the expense of recreating them."

In classic ASP we didn't have anything nearly as sophisticated nor as powerful as the ASP.NET caching API that is now available to us. With .NET we have the ability to cache whole pages (output caching), parts of pages or server controls (fragment caching) and data caching with the lower-level Cache API.

In this article I will be examining data caching in detail. For more information on output caching see Page Output Caching from the ASP.NET QuickStarts. For more information on fragment caching, see Page Fragment Caching from the ASP.NET QuickStarts.

This article was originally published on 4guysfromrolla.com.

Comments

  1. 15 May 2008 at 15:11

    To Access the Pages Cache from class code c#

     

    Cache ce = new Cache();

     

    ce = System.Web.HttpRuntime.Cache; Lol

  2. 30 Apr 2005 at 23:05

    So , Does That mean  this is a Genuine Microsoft Bug??
    No matter What If I Use this Syntax[ Colorede red] to acess the Cache Object I get an Exception...
    internal class EnvUtil ystem.Web.UI.Page {
               
    internal EnvUtil()
    {


    }
    internal  string ResetClientID
    {
    get
    {
    string sResetClientId="";
    try
    {
      if (Cache["ResetClientDoc"] == null)     {
               TextReader xt=new StreamReader(Server.MapPath(@"../../Content/EnvReport/ResetClientID.xml"));


               sResetClientId=xt.ReadToEnd();
               xt.Close();
               CacheDependency dep = new CacheDependency(Server.MapPath(@"../../Content/EnvReport/ResetClientID.xml"), DateTime.Now);


               Cache.Insert("ResetClientDoc", sResetClientId, dep);
       }
       else
       {
               sResetClientId=(string) Cache["ResetClientDoc"];
       }


    }
    catch (Exception ex)
    {
       Debug.WriteLine(ex.Message);
    }
       return sResetClientId;
    }
    }


    }
    }



    Output
    ?ex.Message
    "Cache is not available"



  3. 30 Apr 2005 at 10:01

    Just because the Cache cannot be inherited, doesn't mean you can't access it when you are inheriting the Page class -


    public class MyClass : System.Web.UI.Page {
      public Object SomeMethod() {
         return Cache["SomeObject"];
      }
    }


    is fine. As it's sealed, what you can't do is this:


    public class MyClass : Cache {
      // override or add some methods here
    }

  4. 30 Apr 2005 at 05:00

    I stumbled into this problem. The comment is correct The Cache class is a sealed class, which means it cannot be inherited. Since you are inheriting the Page class in your X testClass the Cache object will  not be available. One way to solve the problem is to pass the Cache object of the Page to the Method that need to process the Cache information as shown in the Sample code..



    <%@ import Namespace="Env" %>
    <%@ import Namespace="System.Xml" %>
    <%@ Page Language="C#" Inherits ="Env.ServerProcess" %>
    <%
       
    XmlDocument xDoc = new  XmlDocument();
    xDoc=ProcessRequest(Request.InputStream,this.Cache);
    Response.ContentType="text/xml";
    Response.Write (xDoc.OuterXml);
    %>
    public class ServerProcess : System.Web.UI.Page
    {
           
       public  XmlDocument ProcessRequest(Stream PageRequestStream,Cache MyCache)
           {
               string sResetClientId="";
              XmlDocument xdoc =new XmlDocument();
                try{
                  if (MyCache ["ResetClientDoc"] == null){
           TextReader xt=new StreamReader(Server.MapPath(@"Content/ResetClientID.xml"));
           sResetClientId=xt.ReadToEnd();
           xt.Close();
           MyCache dep = new CacheDependency(Server.MapPath(@"Content/ResetClientID.xml"), DateTime.Now);
                   
           MyCache.Insert("ResetClientDoc", sResetClientId, dep);}
           Else
    {
              sResetClientId=(string) MyCache ["ResetClientDoc"];


           }
                                 }
                          catch (Exception e){
           System.Diagnostics.Debug.WriteLine( e.Message.ToString())
       }
    xdoc.LoadXml(sResetClientId);
    return xdoc;
       
    }

  5. 23 Mar 2005 at 14:15

    Hi Charlie,

    You can use .NET remoting when you need to keep your cache across processes. The process is discussed here Using Remoting Singleton Caching.

    Hope this helps.

    -DM
  6. 23 Mar 2005 at 14:08
    Hi all, this article unfortunately doesn't deal with class caching. However, in my latest article posted here on DeveloperFusion -Building a Full-Featured Custom DataGrid Control -  I do just that. I demonstrate how to cache an object, in this case the Datagrid, within a class using either the Session or Web Cache API.

    As for caching across processes, you'll need to use .NET remoting. The process is discussed here The process is discussed here Using Remoting Singleton Caching.

    Hope this helps.

    -DM
  7. 16 Jul 2004 at 02:33

    Yes I have tried that as well. IMHO: The thing is that you are trying to access a cache object from a class. But the documentation says that the Cache object cannot be inherited. therefore I would expect it to throw a "Cache is not available" exception. Now this is a real bugger specially when you want to cache data across process/pages. This is precisely what I'm trying to do right now and I have yet to find a solution. Help anyone?

  8. 07 Apr 2004 at 15:17

    How would one use the .NET cache object to keep caches accurate across processes?


    --Charlie



  9. 01 Mar 2004 at 09:55

    On what line does the error occur?

  10. 19 Feb 2004 at 09:53
    I created a class to test the data cache. Any help where to use cache?

    // test.cs
    //

    namespace xtest {
       using System;
       using System.Web;
       using System.Web.Caching;
       public class xtest {

           public static Cache srvCache = new Cache();

           public xtest() {}
           public static string getCache(string key){

               try {
               object strServer= 0;

                   if (srvCache["ServerString"] == null)
                     srvCache["ServerString"]=key;

                   strServer = srvCache.Get("ServerString");

                   return (string) strServer;
               }
               catch (Exception e)
               {
                   return "error: getCache() - "+ e.Message;
               }

           }
       }
    }

    When I run the below mentioned aspx. I get error:
                                   - Object reference not set to an instance of an object.


    <%@ Page Language="C#" %>
    <%@ import Namespace="xtest" %>
    <script runat="server">

       void Page_Load(object sender, EventArgs e) {


                Response.Write(xtest.getCache("X-STAGE"));

       }

    </script>
    <html>
    <head>
    </head>
    <body>
       <form runat="server">
           <!-- Insert content here -->
       </form>
    </body>
    </html>


  11. 01 Jan 1999 at 00:00

    This thread is for discussions of .NET Data Caching.

Leave a comment

Sign in or Join us (it's free).

Dimitrios Markatos Dimitrios, or Jimmy as his friends call him, is a .NET developer/architect who specializes in Microsoft Technologies for creating high-performance and scalable data-driven enterprise Web and deskto...

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!