This documentation is archived and is not being maintained.

MemoryCache Class

Represents the type that implements an in-memory cache.


Namespace:  System.Runtime.Caching
Assembly:  System.Runtime.Caching (in System.Runtime.Caching.dll)

public class MemoryCache : ObjectCache, 
	IEnumerable, IDisposable

The MemoryCache type exposes the following members.

Public methodMemoryCacheInitializes a new instance of the MemoryCache class.

Public propertyCacheMemoryLimitGets the amount of memory on the computer, in bytes, that can be used by the cache.
Public propertyStatic memberDefaultGets a reference to the default MemoryCache instance.
Public propertyDefaultCacheCapabilitiesGets a description of the features that the cache provides. (Overrides ObjectCache.DefaultCacheCapabilities.)
Public propertyItemGets or sets a value in the cache by using the default indexer property for an instance of the MemoryCache class. (Overrides ObjectCache.Item[String].)
Public propertyNameGets the name of the cache. (Overrides ObjectCache.Name.)
Public propertyPhysicalMemoryLimitGets the percentage of physical memory that the cache can use.
Public propertyPollingIntervalGets the maximum time after which the cache updates its memory statistics.

Public methodAdd(CacheItem, CacheItemPolicy)When overridden in a derived class, tries to insert a cache entry into the cache as a CacheItem instance, and adds details about how the entry should be evicted. (Inherited from ObjectCache.)
Public methodAdd(String, Object, DateTimeOffset, String)When overridden in a derived class, inserts a cache entry into the cache without overwriting any existing cache entry. (Inherited from ObjectCache.)
Public methodAdd(String, Object, CacheItemPolicy, String)When overridden in a derived class, inserts a cache entry into the cache, specifying information about how the entry will be evicted. (Inherited from ObjectCache.)
Public methodAddOrGetExisting(CacheItem, CacheItemPolicy)Adds a cache entry into the cache using the specified CacheItem instance and details about how to evict the entry. (Overrides ObjectCache.AddOrGetExisting(CacheItem, CacheItemPolicy).)
Public methodAddOrGetExisting(String, Object, DateTimeOffset, String)Adds a cache entry into the cache using the specified key and a value and an absolute expiration value. (Overrides ObjectCache.AddOrGetExisting(String, Object, DateTimeOffset, String).)
Public methodAddOrGetExisting(String, Object, CacheItemPolicy, String)Inserts a cache entry into the cache using the specified key and value and the specified details for how it is to be evicted. (Overrides ObjectCache.AddOrGetExisting(String, Object, CacheItemPolicy, String).)
Public methodContainsDetermines whether a cache entry exists in the cache. (Overrides ObjectCache.Contains(String, String).)
Public methodCreateCacheEntryChangeMonitorCreates a CacheEntryChangeMonitor object that can trigger events in response to changes to specified cache entries. (Overrides ObjectCache.CreateCacheEntryChangeMonitor(IEnumerable<String>, String).)
Public methodDisposeReleases all resources that are used by the current instance of the MemoryCache class.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetReturns an entry from the cache. (Overrides ObjectCache.Get(String, String).)
Public methodGetCacheItemReturns the specified entry from the cache as a CacheItem instance. (Overrides ObjectCache.GetCacheItem(String, String).)
Public methodGetCountReturns the total number of cache entries in the cache. (Overrides ObjectCache.GetCount(String).)
Protected methodGetEnumeratorCreates an enumerator that can be used to iterate through a collection of cache entries. (Overrides ObjectCache.GetEnumerator().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodGetValues(IEnumerable<String>, String)Returns a set of cache entries that correspond to the specified keys. (Overrides ObjectCache.GetValues(IEnumerable<String>, String).)
Public methodGetValues(String, String[])Gets a set of cache entries that correspond to the specified keys. (Inherited from ObjectCache.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodRemoveRemoves a cache entry from the cache. (Overrides ObjectCache.Remove(String, String).)
Public methodSet(CacheItem, CacheItemPolicy)Inserts a cache entry into the cache by using a CacheItem instance to supply the key and value for the cache entry. (Overrides ObjectCache.Set(CacheItem, CacheItemPolicy).)
Public methodSet(String, Object, DateTimeOffset, String)Inserts a cache entry into the cache by using a key and a value and specifies time-based expiration details. (Overrides ObjectCache.Set(String, Object, DateTimeOffset, String).)
Public methodSet(String, Object, CacheItemPolicy, String)Inserts a cache entry into the cache by using a key and a value and eviction. (Overrides ObjectCache.Set(String, Object, CacheItemPolicy, String).)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodTrimRemoves a specified percentage of cache entries from the cache object.

Public Extension MethodAsParallelEnables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryableConverts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodCast<TResult>Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodOfType<TResult>Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)

Explicit interface implemetationPrivate methodIEnumerable.GetEnumeratorProvides support for iteration over a generic collection.
Explicit interface implemetationPrivate methodIEnumerable<KeyValuePair<String, Object>>.GetEnumeratorSupports iteration over a strongly typed collection. (Inherited from ObjectCache.)

The MemoryCache class is a concrete implementation of the abstract ObjectCache class.


The MemoryCache class is similar to the ASP.NET Cache class. The MemoryCache class has many properties and methods for accessing the cache that will be familiar to you if you have used the ASP.NET Cache class. The main differences between the Cache and MemoryCache classes are that the MemoryCache class has been changed to make it usable by .NET Framework applications that are not ASP.NET applications. For example, the MemoryCache class has no dependencies on the System.Web assembly. Another difference is that you can create multiple instances of the MemoryCache class for use in the same application and in the same AppDomain instance.

The MemoryCache class does not allow null as a value in the cache. Any attempt to add or change a cache entry with a value of null will fail.

The MemoryCache type does not implement cache regions. Therefore, when you call MemoryCache methods that implement base methods that contain a parameter for regions, do not pass a value for the parameter. The methods that use the region parameter all supply a default null value. For example, the MemoryCache.AddOrGetExisting method overload has a regionName parameter whose default value is null.

The following example declares a reference to the default memory cache instance. The cache entry uses a CacheItemPolicy object to provide eviction and expiration details for the cache entry. It also uses a ChangeMonitor object to monitor the state of the source data (which is a file) on the file system.

Private Sub btnGet_Click(ByVal sender As Object, ByVal e As EventArgs) 
    Dim cache As ObjectCache = MemoryCache.[Default] 
    Dim fileContents As String = TryCast(cache("filecontents"), String) 
    If fileContents Is Nothing Then 
        Dim policy As New CacheItemPolicy() 
        Dim filePaths As New List(Of String)() 
        policy.ChangeMonitors.Add(New HostFileChangeMonitor(filePaths)) 
        ' Fetch the file contents.
        fileContents = File.ReadAllText("c:\cache\example.txt") 
        cache.[Set]("filecontents", fileContents, policy) 
    End If 
    Label1.Text = fileContents
End Sub

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>();


        // Fetch the file contents.
        fileContents = 
        cache.Set("filecontents", fileContents, policy);

    Label1.Text = fileContents;

.NET Framework

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.