Accessing ASP.NET Cache from multiple threads

M

Michael Vanhoutte

I was wondering how multiple threads can access the ASP.NET cache object
safely. Take for example the following code that I got from the ASP.NET Cache
object documentation:

DataView Source = (DataView)Cache["MyData1"];
if (Source == null) {
// Connecting to a database...
// Filling a dataset...

Source = new DataView(ds.Tables["Authors"]);
Cache["MyData1"] = Source;
}
MyDataGrid.DataSource=Source;
MyDataGrid.DataBind();


The following questions come to my mind:
1. What happens if two threads reach the 'if (source == null)'-line
simultaneously.
They could both start refilling the cache. Do I need to use locks or mutexes
myself if I want to prevent that?

2. Suppose that thread 1 executed the 'if (source2 == null)' line and found
that that source2 wasn't null. What if thread 2 executed
'Cache.Remove("MyData1")' after thread 1 performed that test but before it
had to change to actually use the value in MyData1.

I would grealy appreciate any feedback!
Michael
 
M

Michael Vanhoutte

I just replied myself so that it is also posted in
dotnet.framework.aspnet.caching. This newsgroups was probably a better place
to post this question. This was my question:

I was wondering how multiple threads can access the ASP.NET cache object
safely. Take for example the following code that I got from the ASP.NET Cache
object documentation:

DataView Source = (DataView)Cache["MyData1"];
if (Source == null) {
// Connecting to a database...
// Filling a dataset...

Source = new DataView(ds.Tables["Authors"]);
Cache["MyData1"] = Source;
}
MyDataGrid.DataSource=Source;
MyDataGrid.DataBind();


The following questions come to my mind:
1. What happens if two threads reach the 'if (source == null)'-line
simultaneously.
They could both start refilling the cache. Do I need to use locks or mutexes
myself if I want to prevent that?

2. Suppose that thread 1 executed the 'if (source2 == null)' line and found
that that source2 wasn't null. What if thread 2 executed
'Cache.Remove("MyData1")' after thread 1 performed that test but before it
had to change to actually use the value in MyData1.

I would grealy appreciate any feedback!
Michael
 
J

joker

This news group is for classic ASP none of the .net stuff. I'd suggest
posting in a newsgroup that includes .net in the name for .net problems.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top