Using Caching properly

  • Thread starter Thread starter Chris Zopers
  • Start date Start date
C

Chris Zopers

Hello,

In my ASP.NET projects I often use caching (like Cache["somename"] =
someObject).

On the internet I read different opinions on this. Some saying "use
cache in every layer and as much as possible", others saying "use cache
sparingly, because it uses up server memory".

I thought the server clears items from the cache when it needs memory,
so the memory-issue isn't really an issue, or is it?

But having said that, I often do something like:

if (Cache["somename"] == null)
{
//Add to the Cache
}

But even if the server removed the item when it needs the memory, the
item is shortly after that being cached again!

I just wonder what is a proper way to use the Cache?

Greetings,
Chris
 
Managing state is not a simple topic. There are several mechanisms to do it
(cache, session, application, cookies, hidden form fields, data stores) and
no one solution works the best in all cases.

In general, just because the .NET Garbage Collector's job is to try to free
up memory when memory is needed, shouldn't be an excuse for not writing
good, efficient code.

That said, you should not rely on client-side caching mechanisms for
application-critical data since the client has control over the data. This
is a security and a functionality issue.

When it comes to server-side caching techniques (such as using the
Application.Cache), security and overhead become the main concerns. Don't
use cache, simply because you can, use it when you don't need a long-term
storage solution, you want to reduce the complexity of your application's
logic, and the data stored in the cache is not sensitive.

With this in mind, you can use the cache for only those situations that
warrant it.

-Scott
 
Back
Top