What is difference between MemoryCache vs ObjectCache in .net 4.0?

前端 未结 3 2044
不思量自难忘°
不思量自难忘° 2021-02-02 05:35

What is difference between .NET framework 4.0 MemoryCache vs ObjectCache? Where to use which object?

相关标签:
3条回答
  • 2021-02-02 06:26

    From MSDN;

    The ObjectCache type is the primary type for the in-memory object cache. The built-in MemoryCache class derives from the ObjectCache class. The MemoryCache class is the only concrete object cache implementation in the .NET Framework 4 that derives from the ObjectCache class.

    public class MemoryCache : ObjectCache, 
        IEnumerable, IDisposable
    

    MemoryCache inherits from ObjectCache.

    You can get a reference to the default MemoryCache instance like this;

    public static ObjectCache cache = MemoryCache.Default;
    
    0 讨论(0)
  • 2021-02-02 06:29

    ObjectCache is an abstract class, you can't 'use' it per se. As Dash says in his comment, it's designed to show how a cache should be built and what operations it supports. MemoryCacheis an implementation of ObjectCache and from your question is likely what you should use. However, because ObjectCache is abstract, you could just as easily write your own FileCache inheriting from ObjectCache and it would be perfectly valid.

    0 讨论(0)
  • 2021-02-02 06:33

    ObjectCache is the abstract class that demonstrates how you should build a Cache that adheres to the rules the person who wrote ObjectCache wants you to obey. You cannot instantiate ObjectCache directly as it is abstract.

    MemoryCache is an actual implementation of ObjectCache.

    From the documentation:

    ObjectCache

    Represents an object cache and provides the base methods and properties for accessing the object cache.

    MemoryCache

    Represents the type that implements an in-memory cache.

    Looking at the declaration for MemoryCache:

    public class MemoryCache : ObjectCache, 
        IEnumerable, IDisposable
    

    We can see that MemoryCache inherits from ObjectCache - that is, it's an cache for objects that uses Memory as its storage - this is therefore an implementation of ObjectCache.

    You could write your own; for example, DatabaseCache, which could also inherit from ObjectCache but instead it would use a database as the backing storage.

    For everyday use, provided it met your needs, you would use and consume a MemoryCache. If you wanted to write your own, you could inherit from ObjectCache and implement the required methods and properties. However, in reality, there is probably little practical benefit to doing this as Microsoft already make several other caching solutions available, as do many other vendors.

    0 讨论(0)
提交回复
热议问题