Spencer Ruport
Spencer Ruport

Reputation: 35117

ASP.Net static objects

I'm trying to cache some information that I've retrieved from a database. I've decided to use a static List<> member to store the information. I know from my experience with List<> in multithreaded applications that I need to protect access to it with the lock statement. Do I treat any code in my Asp.Net code the exact same way? Will the lock statement still work?

Upvotes: 1

Views: 1241

Answers (3)

DOK
DOK

Reputation: 32851

It depends upon whether you're going to modify the List. Here's a good discussion of this subject: Do i need a lock on a list? C#

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039060

A lock statement around List method's would definitely work but if you need caching functionality in your ASP.NET application I would recommend you using Cache class which is adapted to this functionality.

Upvotes: 5

Andomar
Andomar

Reputation: 238166

Lock will work. Be aware that if there are multiple worker processes, you will end up with multiple versions of the list. Each of them will be protected by its own lock.

A pretty real danger here is that if you fail to release the lock, your entire web application might hang. A user might get disconnected while your ASP.NET page is executing; so be careful of exceptions thrown at unexpected times.

Upvotes: 2

Related Questions