Correct using Cache in ASP.NET

Jan 12
2008 21:22 (ASP.NET, Development) · Русский (5,660 views)

Often in ASP.NET application we see a code which looks like this one:

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:

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)

Tagged ,

5 Responses to 'Correct using Cache in ASP.NET'

Subscribe to comments with RSS or TrackBack to 'Correct using Cache in ASP.NET'.

1
said on 2008-01-14 at 1.43 am

спасибо…частенько встречался с подобным багом и руки опускались из-за неопытности :)

2
AM
said on 2008-04-04 at 8.06 pm

я если честно не понял почему в первом случае может появиться NullReferenceException, ведь там проверка на null есть? и почему тогда не появится во втором.

3
said on 2008-06-14 at 2.12 pm

Тоже не особо понял. Первый вариант часто приводится в различных книгах.

4
Sergey
said on 2008-10-02 at 10.54 pm

Использую первый вариант уже долгое время, никаких багов не замечал, к тому же всегда выставляю время хранения кэша. Обычно при пустом кэше происходит секундная заминка, но в целом все работает нормально.

5
said on 2008-10-08 at 9.11 am

Правильное использование кэша в ASP.NET…

Все дело в механизме работы кэша в ASP.NET. В идеальном случае объект, помещенный в кэш, будет храниться там до перезагрузки приложения, но на …

Post a comment

You can use simple HTML-formatting tags (like <a>, <ul> and others). To format your code sample use <code lang="php">$a = "hello";</code> (allowed languages are ruby, php, yaml, html, csharp, javascript). Also you could use <code>$a = "hello";</code> and its syntax would not be highlighted. If you are not using <code> tag, replace < sign with &lt;.

Submit Comment

 
Copyright © 2005 - 2008, Dmytro Shteflyuk