tags:

views:

719

answers:

3

Hello community,

I wanted to ask you what is the best approach to implement a cache in C#? Is there a possibility by using given .Net-classes or something like that? Perhaps something like a dictionary that will remove some entries if it gets too large but whose entries won't be removed by the garbage collector?

Thanks in advance

Sebastian

A: 

You could use a Hashtable

it has very fast lookups, no key collisions and your data will not garbage collected

Toad
but what if the hashtables becomes too big?
Xelluloid
The only thing which might happen is that you run out of memory. If this is not the case, the hashtable runs fine. Internally it fixes key collisions it might encounter so you won't notice it.
Toad
Hashtable is not a cache, it is a lookup (if used for this purpose). A Cache has expiry, scavenging, capacity management and sometimes transaction support, freezing and many other features. Look at Caching Application Block although it forces you to bring in the whole farm of other Application Blocks and is very configuration heavy.
Khash
+3  A: 

If you're using asp.net you could use the Cache class (System.Web.Caching).

Here is a good helper class: link text

If you mean caching in a windows form app, it depends on what you're trying to do, and where you're trying to cache the data.

We've implemented a Cache behind a webservice for certain methods
(Using the System.Web.Caching object.).

However you might also want to look at the Caching Application Block. (See here)
Which is part of the Enterprise Library for .NET Framework 2.0

Bravax
it doesn't say he uses asp.net
Toad
I suggested an option for asp.net as well as an approach for when you're not. (Caching Application Block).
Bravax
Does not matter if it is asp.net or not. You can reference System.Web in a desktop application and use System.Web.Cache through HttpRuntime.Cache property.
Ricardo Nolde
A: 

If you are looking to Cache something in ASP.Net then I would look at the Cache class. For example

Hashtable menuTable = new Hashtable(); 
menuTable.add("Home","default.aspx"); 
Cache["menu"] = menuTable;

Then to retrieve it again

Hashtable menuTable = (Hashtable)Cache["menu"];
uriDium