Difference between HttpRuntime.Cache and HttpContext.Current.Cache?

asp.net

asp.net Problem Overview


What is the difference between HttpRuntime.Cache and HttpContext.Current.Cache?

asp.net Solutions


Solution 1 - asp.net

I find following detail from http://theengineroom.provoke.co.nz/archive/2007/04/27/caching-using-httpruntime-cache.aspx

> For caching I looked into using > HttpContext.Current.Cache but after > reading other blogs I found that > caching using HttpContext uses > HttpRuntime.Cache to do the actual > caching. The advantage of using > HttpRuntime directly is that it is > always available, for example, in > Console applications and in Unit > tests. > > Using HttpRuntime.Cache is simple. > Objects can be stored in the cache and > are indexed by a string. Along with a > key and the object to cache the other > important parameter is the expiry > time. This parameter sets the time > before the object is dropped from the > cache.

Here is good link for you.

Another good resource.

Solution 2 - asp.net

Caching using HttpContext uses HttpRuntime.Cache to do the actual caching. The advantage of using HttpRuntime directly is that it is always available in console applications and in unit tests.

Solution 3 - asp.net

Using HttpRuntime.Cache is simple to use than HttpContext.Current.Cache.As already said that objects can be stored in the cache and are indexed by a string.Also in unit test and console HttpRuntime this available.

Here is an example to use HttpRuntime.Cache.

public static XmlDocument GetStuff(string sKey) 
{
XmlDocument xmlCodes;
xmlCodes = (XmlDocument) HttpRuntime.Cache.Get( sKey );
if (xmlCodes == null)
{
      xmlCodes = SqlHelper.ExecuteXml(new dn("Nodes", "Node"), "Get_Stuff_From_Database", sKey);
      HttpRuntime.Cache.Add(sKey, xmlCodes, null,
      DateTime.UtcNow.AddMinutes(1.0),
      System.Web.Caching.Cache.NoSlidingExpiration,
      System.Web.Caching.CacheItemPriority.Normal, null);
}
return xmlCodes;
}

What this example does actually:

The method GetStuff takes a string parameter which is used to retrieve a set of items from the database. The method first checks to see if an XmlDocument indexed by the parameter key is in the cache. If it is, it simply returns this object, if not it queries database. After it has retrieved the document from the database it then put it into cache. If this method is called again within the stipulated time, it will get the object rather than hitting the database.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTushar MaruView Question on Stackoverflow
Solution 1 - asp.netSyed Tayyab AliView Answer on Stackoverflow
Solution 2 - asp.netWayne HartmanView Answer on Stackoverflow
Solution 3 - asp.netNavoneel TalukdarView Answer on Stackoverflow