views:

172

answers:

2

As per title. I want to be able to save some data in a cache object but this object must be available to all users/sessions and can expire.

What is the best method to achieve this in a asp.net web app?

+3  A: 

HttpContext.Current is available to all pages, but not necessarily to all threads. If you try to use it inside a background thread, ThreadPool delegate, async call (using an ASP.NET Async page), etc., you'll end up with a NullReferenceException.

If you need to get access to the cache from library classes, i.e. classes that don't have knowledge of the current request, you should use HttpRuntime.Cache instead. This is more reliable because it doesn't depend on an HttpContext.

Aaronaught
@Aaronnaught - I'm not sure how there is a difference beyond access to HttpContext.Current since HttpContext.Current.Cache returns HttpRuntime.Cache.
Thomas
@Aaronnaught - I suppose you are saying that not having to depend on HttpContext.Current is in fact that advantage?
Thomas
+1, HttpContext.Current should be used with care.
kervin
@Thomas: `HttpContext.Current.Cache` just points to the same cache as `HttpRuntime.Cache` anyway, but the former introduces an intermediate dependency that has the potential to break something later. Search for "HttpContext NullReferenceException" here on SO and you'll see what I mean...
Aaronaught
@Aaronaught - Hmm. Ok. I've never encountered an error referencing HttpContext.Current, but given what I've read, I'll buy that HttpRuntime.Cache would be a better choice. +1.
Thomas
+1  A: 

HttpContext.Current.Cache will be present, but Current should only be used if you cant get to your context member.

Also to answer your second question, yes, the Cache object is global to the application.

Here's a good intro to caching...

How to cache in ASP.NET by using Visual C# .NET

and...

Caching with ASP.NET . Don't skip part 2, "Data Caching"

kervin