Often in ASP.NET application we see a code which looks like this one:
1 2 3 4 5 | if (Cache["SomeData"] != null) { string name = ((SomeClass) Cache["SomeData"]).Name; //..... } |
Experienced developer, even if he is not a paranoiac, will find possible problem immediately — NullReferenceException. That’s because of caching implementation in ASP.NET. In ideal case an object, that has been cached, will stay there up to application restart, but in real world it could be deleted between two calls: by the garbage collector when memory is over (because cache uses weak references WeakReference); by another thread to refresh cached data.
So the code I have mentioned before works in 99% of all cases, but sometimes you will get errors in your log, which can not be reproduced easily. Here is right cache usage approach:
1 2 3 4 5 6 | SomeClass someClass = Cache["SomeData"] as SomeClass; if (someClass != null) { string name = someClass.Name; //..... } |
Do not relax your vigilance, it’s exactly what they are waiting for! (about bugs)