简体   繁体   中英

What is difference between normal cache class and MemoryCache class?

What is the 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 is it 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 does the above code do? Is it monitoring file content change?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM