【问题标题】:What is difference between normal cache class and MemoryCache class?普通缓存类和 MemoryCache 类有什么区别?
【发布时间】:2015-09-03 18:14:58
【问题描述】:

普通缓存类和MemoryCache类有什么区别?

缓存是指存储在内存中的数据。那为什么要给 MemoryCache 额外的类呢?

MemoryCache 类的用途是什么?什么时候使用它来代替普通的缓存类?

请看下面的示例代码

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;
}

上面的代码是做什么的?是否监控文件内容变化?

【问题讨论】:

标签: asp.net memorycache


【解决方案1】:

HttpRuntime.Cache 获取当前应用程序的缓存。
看这里
msdn

MemoryCache 是存储在内存中的缓存。 表示实现内存缓存的类型。
msdn

这是一个很好的博客,可以解决您的所有疑虑blog
仅从该博客中摘录了几行。

msdn 说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.

尽管 Microsoft 一直坚称 ASP.NET 缓存不适合在 Web 之外使用。但是很多人仍然停留在 .NET 2.0 和 .NET 3.5 中,需要一些东西来使用。

Microsoft 最终在 .NET Framework 的最新版本中实现了一个抽象 ObjectCache 类,以及一个 MemoryCache 实现,该实现在非 Web 设置中继承和实现 ObjectCache 以用于内存中的目的。 System.Runtime.Caching.ObjectCache 在 System.Runtime.Caching.dll 程序集中。它是一个抽象类,它声明了与 ASP.NET 缓存中的基本相同的 .NET 1.0 样式接口。

System.Runtime.Caching.MemoryCache 是 ObjectCache 的内存实现,与 ASP.NET 缓存非常相似,只是有一些变化。

【讨论】:

  • 我猜 Cache 类也将数据存储在内存中,而 MemoryCache 又是一个存储在内存中的缓存......那么有什么区别?
  • 解释不是很清楚用法,因为这两个类都是内存常驻的。
猜你喜欢
  • 2011-02-25
  • 2022-08-19
  • 2023-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多