MemoryCache MemoryCache MemoryCache MemoryCache Class

Definition

Represents the type that implements an in-memory cache.

public ref class MemoryCache : System::Runtime::Caching::ObjectCache, IDisposable
public class MemoryCache : System.Runtime.Caching.ObjectCache, IDisposable
type MemoryCache = class
    inherit ObjectCache
    interface IEnumerable
    interface IDisposable
Public Class MemoryCache
Inherits ObjectCache
Implements IDisposable
Inheritance
MemoryCacheMemoryCacheMemoryCacheMemoryCache
Implements

Examples

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

Remarks

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

Note

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.

Constructors

MemoryCache(String, NameValueCollection) MemoryCache(String, NameValueCollection) MemoryCache(String, NameValueCollection) MemoryCache(String, NameValueCollection)

Initializes a new instance of the MemoryCache class.

MemoryCache(String, NameValueCollection, Boolean) MemoryCache(String, NameValueCollection, Boolean) MemoryCache(String, NameValueCollection, Boolean) MemoryCache(String, NameValueCollection, Boolean)

Initializes a new instance of the MemoryCache class.

Properties

CacheMemoryLimit CacheMemoryLimit CacheMemoryLimit CacheMemoryLimit

Gets the amount of memory on the computer, in bytes, that can be used by the cache.

Default Default Default Default

Gets a reference to the default MemoryCache instance.

DefaultCacheCapabilities DefaultCacheCapabilities DefaultCacheCapabilities DefaultCacheCapabilities

Gets a description of the features that the cache provides.

Item[String] Item[String] Item[String] Item[String]

Gets or sets a value in the cache by using the default indexer property for an instance of the MemoryCache class.

Name Name Name Name

Gets the name of the cache.

PhysicalMemoryLimit PhysicalMemoryLimit PhysicalMemoryLimit PhysicalMemoryLimit

Gets the percentage of physical memory that the cache can use.

PollingInterval PollingInterval PollingInterval PollingInterval

Gets the maximum time after which the cache updates its memory statistics.

Methods

Add(CacheItem, CacheItemPolicy) Add(CacheItem, CacheItemPolicy) Add(CacheItem, CacheItemPolicy) Add(CacheItem, CacheItemPolicy)

Inserts a cache entry into the cache as a CacheItem instance, and adds details about how the entry should be evicted.

Add(String, Object, CacheItemPolicy, String) Add(String, Object, CacheItemPolicy, String) Add(String, Object, CacheItemPolicy, String) Add(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)
Add(String, Object, DateTimeOffset, String) Add(String, Object, DateTimeOffset, String) Add(String, Object, DateTimeOffset, String) Add(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)
AddOrGetExisting(CacheItem, CacheItemPolicy) AddOrGetExisting(CacheItem, CacheItemPolicy) AddOrGetExisting(CacheItem, CacheItemPolicy) AddOrGetExisting(CacheItem, CacheItemPolicy)

Adds a cache entry into the cache using the specified CacheItem instance and details about how to evict the entry.

AddOrGetExisting(String, Object, CacheItemPolicy, String) AddOrGetExisting(String, Object, CacheItemPolicy, String) AddOrGetExisting(String, Object, CacheItemPolicy, String) AddOrGetExisting(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.

AddOrGetExisting(String, Object, DateTimeOffset, String) AddOrGetExisting(String, Object, DateTimeOffset, String) AddOrGetExisting(String, Object, DateTimeOffset, String) AddOrGetExisting(String, Object, DateTimeOffset, String)

Adds a cache entry into the cache using the specified key and a value and an absolute expiration value.

Contains(String, String) Contains(String, String) Contains(String, String) Contains(String, String)

Determines whether a cache entry exists in the cache.

CreateCacheEntryChangeMonitor(IEnumerable<String>, String) CreateCacheEntryChangeMonitor(IEnumerable<String>, String) CreateCacheEntryChangeMonitor(IEnumerable<String>, String) CreateCacheEntryChangeMonitor(IEnumerable<String>, String)

Creates a CacheEntryChangeMonitor object that can trigger events in response to changes to specified cache entries.

Dispose() Dispose() Dispose() Dispose()

Releases all resources that are used by the current instance of the MemoryCache class.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Get(String, String) Get(String, String) Get(String, String) Get(String, String)

Returns an entry from the cache.

GetCacheItem(String, String) GetCacheItem(String, String) GetCacheItem(String, String) GetCacheItem(String, String)

Returns the specified entry from the cache as a CacheItem instance.

GetCount(String) GetCount(String) GetCount(String) GetCount(String)

Returns the total number of cache entries in the cache.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Creates an enumerator that can be used to iterate through a collection of cache entries.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLastSize(String) GetLastSize(String) GetLastSize(String) GetLastSize(String)

Gets the size of the named region.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetValues(IEnumerable<String>, String) GetValues(IEnumerable<String>, String) GetValues(IEnumerable<String>, String) GetValues(IEnumerable<String>, String)

Returns a set of cache entries that correspond to the specified keys.

GetValues(String, String[]) GetValues(String, String[]) GetValues(String, String[]) GetValues(String, String[])

Gets a set of cache entries that correspond to the specified keys.

(Inherited from ObjectCache)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Remove(String, CacheEntryRemovedReason, String) Remove(String, CacheEntryRemovedReason, String) Remove(String, CacheEntryRemovedReason, String) Remove(String, CacheEntryRemovedReason, String)

Removes a cache entry from the cache using the reason.

Remove(String, String) Remove(String, String) Remove(String, String) Remove(String, String)

Removes a cache entry from the cache.

Set(CacheItem, CacheItemPolicy) Set(CacheItem, CacheItemPolicy) Set(CacheItem, CacheItemPolicy) Set(CacheItem, CacheItemPolicy)

Inserts a cache entry into the cache by using a CacheItem instance to supply the key and value for the cache entry.

Set(String, Object, CacheItemPolicy, String) Set(String, Object, CacheItemPolicy, String) Set(String, Object, CacheItemPolicy, String) Set(String, Object, CacheItemPolicy, String)

Inserts a cache entry into the cache by using a key and a value and eviction.

Set(String, Object, DateTimeOffset, String) Set(String, Object, DateTimeOffset, String) Set(String, Object, DateTimeOffset, String) Set(String, Object, DateTimeOffset, String)

Inserts a cache entry into the cache by using a key and a value and specifies time-based expiration details.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)
Trim(Int32) Trim(Int32) Trim(Int32) Trim(Int32)

Removes a specified percentage of cache entries from the cache object.

Explicit Interface Implementations

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

Provides support for iteration over a generic collection.

IEnumerable<KeyValuePair<String,Object>>.GetEnumerator() IEnumerable<KeyValuePair<String,Object>>.GetEnumerator() IEnumerable<KeyValuePair<String,Object>>.GetEnumerator() IEnumerable<KeyValuePair<String,Object>>.GetEnumerator()

Supports iteration over a strongly typed collection.

(Inherited from ObjectCache)

Extension Methods

CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>)

Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName)

Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>)

Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>)

Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName)

Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>)

Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName)

Returns a filtered collection of the child elements of every element and document in the source collection. Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>)

Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>)

Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>)

Removes every node in the source collection from its parent node.

Applies to

Thread Safety

This type is thread safe.

See also