Accessing ASP.NET Cache from multiple threads

From: Michael Vanhoutte (MichaelVanhoutte_at_discussions.microsoft.com)
Date: 08/21/04


Date: Sat, 21 Aug 2004 02:51:01 -0700

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



Relevant Pages

  • Interview Questions May 1st, 2006
    ... What's the difference between Cache object and application object? ... What are dependencies in cache and types of dependencies? ... 1000 Interview Questions for .NET and SQL Server ...
    (comp.programming)
  • Re: OutputCache?
    ... you tell it to cache. ... The Cache object also isn't guaranteed not to drop. ... DataSet gets created by explicitly retrieving the records from the DB ... will expire & a Label which displays from where the records are being ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: OutputCache?
    ... cache for X seconds, that could be one of the reasons why the code I ... Here I am adding a DataSet to the cache using the Cache object. ... DataSet gets created by explicitly retrieving the records from the DB ... will expire & a Label which displays from where the records are being ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: Using global callback function with cache object
    ... There is no such thing as logoff in a web ... As for using the Cache object for this - why would you want to logoff users ... >> expires. ...
    (microsoft.public.dotnet.framework.aspnet)
  • singleton serialization and weblogic - help!
    ... I'm trying to serialize a singleton cache object we're using for our ... Basically I've written a jsp to get the current instance of the cache ...
    (comp.lang.java.programmer)