Is there any nasty side if I block the HttpContext.Current.Cache.Insert method

Apart from blocking other threads reading from the cache, what other problems should I be thinking about when blocking the cache insert method for a public site.

The actual fetching of the data and inserting into the cache takes no more than 1 second, which we can live with. More importantly, I don't want multiple threads to potentially use the Insert method at the same time.

An example code looks something like this:

public static readonly object _syncRoot = new object();

if (HttpContext.Current.Cache["key"] == null)
{
  lock (_syncRoot)
  {
    HttpContext.Current.Cache.Insert("key", "DATA", null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
  }
}

  Response.Write(HttpContext.Current.Cache["key"]);

      

+2


a source to share


1 answer


I expect you to do this to prevent data extraction more than once, possibly because the amount of data is high, which can affect your server when multiple users run this extraction.

A lock like this only on Cache.Insert

is useless because this method is thread safe. Locking like this can be useful to prevent double lookups of data, but in this case you should consider using a double-checked lock:



var  data = HttpContext.Current.Cache["key"];
if (data == null)
{
  lock (_syncRoot)
  {
    // Here, check again for null after the lock.
    var  data = HttpContext.Current.Cache["key"];
    if (data == null)
    {
        var data = [RETRIEVE DATA]
        HttpContext.Current.Cache.Insert("key", data, null, ...);
  }
}
return data;

      

But to your main question. Apart from the risk of blocking for too long a period of time causing big delays in your web application, there is nothing to worry about :-). Blocking around Cache.Insert

by itself won't harm you.

+2


a source







All Articles