views:

327

answers:

5
+1  Q: 

ASP.NET Caching

Recently I have been investigating the possibilities of caching in ASP.NET.

I rolled my own "Cache", because I didn't know any better, it looked a bit like this:

public class DataManager
{

      private static DataManager s_instance;

      public static DataManager GetInstance()
      {
      }

      private Data[] m_myData;
      private DataTime m_cacheTime;

      public Data[] GetData()
      {
            TimeSpan span = DateTime.Now.Substract(m_cacheTime);

            if(span.TotalSeconds > 10)
            {
                  // Do SQL to get data
                  m_myData = data;
                  m_cacheTime = DateTime.Now;
                  return m_myData;     
            }
            else
            {
                  return m_myData;
            }
      }

}

So the values are stored for a while in a singleton, and when the time expires, the values are renewed. If time has not expired, and a request for the data is done, the stored values in the field are returned.

What are the benefits over using the real method (http://msdn.microsoft.com/en-us/library/aa478965.aspx) instead of this?

+4  A: 

I think the maxim "let the computer do it; it's smarter than you" applies here. Just like memory management and other complicated things, the computer is a lot more informed about what it's doing than your are; consequently, able to get more performance than you are.

Microsoft has had a team of engineers working on it and they've probably managed to squeeze much more performance out of the system than would be possible for you to. It's also likely that ASP.NET's built-in caching operates at a different level (which is inaccessible to your application), making it much faster.

DannySmurf
+2  A: 

The ASP.NET caching mechanism has been around for a while, so it's stable and well understood. There are lots of resources out there to help you make the most of it.

Rolling your own might be the right solution, depending on your requirements.

The hard part about caching is choosing what is safe to cache, and when. For applications in which data changes frequently, you can introduce some hard to troubleshoot bugs with caching, so be careful.

Eric Z Beard
A: 

Tip: Since it is static you should probably make it thread safe.

Patrik
+1  A: 

Caching in ASP.NET is feature rich and you can configure caching in quite a granular way.

In your case (data caching) one of the features you're missing out on is the ability to invalidate and refresh the cache if data on the SQL server is updated in some way (SQL Cache Dependency).

http://msdn.microsoft.com/en-us/library/ms178604.aspx

Kev
A: 

You can find info on ASP.NET page caching here: http://msdn.microsoft.com/en-us/library/sfw2210t(v=VS.90).aspx

Digitz