Often in ASP.NET application we see a code which looks like this one:
{
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:
if (someClass != null)
{
string name = someClass.Name;
//.....
}
Do not relax your vigilance, it’s exactly what they are waiting for! (about bugs)
Русский
English
спасибо…частенько встречался с подобным багом и руки опускались из-за неопытности
я если честно не понял почему в первом случае может появиться NullReferenceException, ведь там проверка на null есть? и почему тогда не появится во втором.