17

Normally i have a static class that reads and writes to HttpContext.Current.Cache

However since adding threading to my project, the threads all get null reference exceptions when trying to retrieve this object.

Is there any other way i can access it, workarounds or another cache i can use?

5
  • 2
    It isn't thread-safe. Check out the lock keyword in your favorite C# programming book. Commented Mar 13, 2010 at 0:24
  • What exactly do you mean by "since adding threading"? Commented Mar 13, 2010 at 0:25
  • @nobugz: System.Web.Caching.Cache is thread-safe. No lock needed here. Commented Mar 13, 2010 at 1:37
  • @aaro: is the property thread-safe? Doesn't look it. Commented Mar 13, 2010 at 1:47
  • 3
    @nobugz: HttpContext.Current is thread-local and read-only so basically, yes, it is thread-safe, although it's also wrong for the reasons pointed out by binarycoder below. HttpRuntime.Cache is the same, but globally-accessible; it's not synchronized but it's also immutable, so you don't need to use any explicit locks. In fact, the ASP.NET HttpContext.Cache is just a reference to HttpRuntime.Cache, so it has to be thread-safe, otherwise ASP.NET requests would steamroll each other constantly. Commented Mar 13, 2010 at 2:04

2 Answers 2

37

The System.Web.Cache object itself is thread safe.

The issue is how to obtain a reference to it in a way that works throughout your application. HttpContext.Current returns null unless it is called on a thread that is handling an ASP.NET request. An alternative way to get the Cache is through the static property System.Web.HttpRuntime.Cache. This will avoid the problems with the HttpContext.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh cool, I don't know how I never came across HttpRuntime... +1, deleting my answer. :)
+1: This is the right answer. Here's some details: weblogs.asp.net/pjohnson/archive/2006/02/06/437559.aspx
The pjohnson page has moved to weblogs.asp.net/pjohnson/…. The redirect doesn't work; took a while to find it with wayback machine.
2

If your project is an ASP.NET project, then it was multithreaded even before you "added threading".

Check to see if HttpContext.Current is non-null before referencing HttpContext.Current.Cache.

Also, please post the complete exception you're receiving, and show us the code that references the cache.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.