Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to lock cache in asp.net?

I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache.

What is the best way in c# to implement cache locking in ASP.NET?

like image 756
John Owen Avatar asked Sep 02 '08 09:09

John Owen


People also ask

What is a way to cache an ASP.NET page?

To manually cache application data, you can use the MemoryCache class in ASP.NET. ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory. You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web. config file.

Is ASP.NET cache thread safe?

The use of the cache in the preceding example is functionally correct; however, because the ASP.NET cache object is thread safe, it introduces potential performance problems.

What are the different caching techniques available in .NET MVC?

ASP.NET supports three types of caching: Page Output Caching [Output caching] Page Fragment Caching [Output caching] Data Caching.


2 Answers

Here's the basic pattern:

  • Check the cache for the value, return if its available
  • If the value is not in the cache, then implement a lock
  • Inside the lock, check the cache again, you might have been blocked
  • Perform the value look up and cache it
  • Release the lock

In code, it looks like this:

private static object ThisLock = new object();  public string GetFoo() {    // try to pull from cache here    lock (ThisLock)   {     // cache was empty before we got the lock, check again inside the lock      // cache is still empty, so retreive the value here      // store the value in the cache here   }    // return the cached value here  } 
like image 141
a7drew Avatar answered Oct 26 '22 00:10

a7drew


For completeness a full example would look something like this.

private static object ThisLock = new object(); ... object dataObject = Cache["globalData"]; if( dataObject == null ) {     lock( ThisLock )     {         dataObject = Cache["globalData"];          if( dataObject == null )         {             //Get Data from db              dataObject = GlobalObj.GetData();              Cache["globalData"] = dataObject;         }     } } return dataObject; 
like image 37
John Owen Avatar answered Oct 26 '22 00:10

John Owen