Mou Mou - 3 months ago 13
ASP.NET (C#) Question

what is difference between normal cache class and MemoryCache class?

what is difference between normal cache class and MemoryCache class ?

cache means data stored in memory then why extra class given for MemoryCache ?

what is the purpose of MemoryCache class and when it is used instead of normal cache class?

just see the below example code

private void btnGet_Click(object sender, EventArgs e)
{
ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;

if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();

List<string> filePaths = new List<string>();
filePaths.Add("c:\\cache\\example.txt");

policy.ChangeMonitors.Add(new
HostFileChangeMonitor(filePaths));

// Fetch the file contents.
fileContents =
File.ReadAllText("c:\\cache\\example.txt");

cache.Set("filecontents", fileContents, policy);
}

Label1.Text = fileContents;
}


what the above code does? it is monitoring file content change?

like to understand the flow. thanks

Answer

HttpRuntime.Cache gets the Cache for the current application.
see here
msdn

MemoryCache is a cache stored in memory. Represents the type that implements an in-memory cache.
msdn

Here is an excellent blog that will clear all your concerns blog
Just few lines taken from this blog.

msdn says this
The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.

Although Microsoft has always been adamant that the ASP.NET cache is not intended for use outside of the web. But many people are still stuck in .NET 2.0 and .NET 3.5, and need something to work with.

Microsoft finally implemented an abstract ObjectCache class in the latest version of the .NET Framework, and a MemoryCache implementation that inherits and implements ObjectCache for in-memory purposes in a non-web setting. System.Runtime.Caching.ObjectCache is in the System.Runtime.Caching.dll assembly. It is an abstract class that that declares basically the same .NET 1.0 style interfaces that are found in the ASP.NET cache.

System.Runtime.Caching.MemoryCache is the in-memory implementation of ObjectCache and is very similar to the ASP.NET cache, with a few changes.