Per MSDN:
Using the application cache is similar to using application state. However, unlike application state, the data in the application cache is volatile, meaning it is not stored in memory for the life of the application. The advantage of using the application cache is that ASP.NET manages the cache and removes items when they expire or become invalidated, or when memory runs low. You can also configure application caching to notify your application when an item is removed. For more information see Caching Application Data.
The example code you provided
HttpContext.Current.Application["MyKeyName"] = "Some Data";
is using Application State, not using the Application Cache. Application State has many disadvantages to the Application Cache - namely that it is lost when the application pool recycles, it is not thread-safe, there is no way to make the cache expire, and there is no cache dependency mechanism to make it update automatically if the underlying data store is updated. Application State is generally considered to be an antiquated caching technology. See Application State Considerations for more details.
To use the application cache, you would access it through the HttpContext.Cache
property. Note that in MVC the HttpContext
is available in most places, so you should avoid using the static HttpContext.Current
accessor.
// Get
var value = this.HttpContext.Cache["MyKeyName"];
// Set
this.HttpContext.Cache.Insert(
"MyKeyName",
value,
null,
DateTime.Now.AddMinutes(5),
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable,
null);
There is also a new caching option in .NET 4: System.Runtime.Caching
, which is similar to the application cache, but does not have any dependencies on the System.Web
namespace.