.Net 4.0 implements MemoryCache class to facilitate caching of frequently used data in any application built with .Net.
Assembly Reference: System.Runtime.Caching.dll
// using the default instance of MemoryCache in this example
// default cache is Global to the application
ObjectCache _defaultCache = MemoryCache.Default;
// Alternatively, we can create and use custom instance of MemoryCache
// const String CUSTOM_CACHE_NAME = "MyCache";
// ObjectCache customCache = new MemoryCache(CUSTOM_CACHE_NAME);
// eviction and expiration details for a specific cache entry.
CacheItemPolicy policy = new CacheItemPolicy()
{
// used to determine whether to evict a cache entry
// Priority = CacheItemPriority.NotRemovable,
Priority = CacheItemPriority.Default,
// whether a cache entry should be evicted if it has not been accessed in a given span of time.
SlidingExpiration = TimeSpan.FromMinutes(30),
// Other options
// indicates whether a cache entry should be evicted after a specified duration.
// AbsoluteExpiration = DateTimeOffset.Now.AddHours(1),
// a collection of ChangeMonitor objects that are associated with a cache entry.
// ChangeMonitors = ...
// a reference to a CacheEntryRemovedCallback delegate that is called after an entry is removed from the cache.
// RemovedCallback = ...
// a reference to a CacheEntryUpdateCallback delegate that is called before a cache entry is removed from the cache
// UpdateCallback = ...
};
// an individual entry in the cache
CacheItem item = new CacheItem(
key: Guid.NewGuid().ToString(),
value: DateTime.UtcNow
);
// true if insertion succeeded, or false if there is an already an entry in the cache that has the same key as item
var insertionSucceededBecauseNoneExistedBefore = _defaultCache.Add(item, policy);
// If a cache entry with the same key exists, the existing cache entry; otherwise, null.
var existingItemIfAnyOrNullIfNoneExistedBefore = _defaultCache.AddOrGetExisting(item, policy);
// the Set method always puts a cache value in the cache, regardless whether an entry already exists that has the same key
_defaultCache.Set(item, policy);
// A reference to the cache entry identified by key if the entry exists; otherwise, null.
var cachedItemIfAny = _defaultCache.GetCacheItem(item.Key);
// iterate through all cached items
StringBuilder sb = new StringBuilder();
foreach(var item in _defaultCache)
{
sb.AppendLine(item.Key + "= " + item.Value);
}