- The
ObjectCache
is the primary type for the in-memory object cache resides in System.Runtime.Caching
.
- You can create and manage cache entries in a key/value pair manner.
- Specify expiration and eviction information.
- Trigger events that are raised in response to changes in cache entries.
- All implementations of the
ObjectCache
class should disallow null as a value for cached data.
- This helps avoid confusion between null as a data value and a cache entry that was not found.
- The
MemoryCache
class is an in-memory object cache implementation of the ObjectCache
class.
- Files and Sql databases can be monitored for changes, invalidating the cache when the data of interest is changed.
- The
HostFileChangeMonitor
is use to track the state of a file, and SqlChangeMonitor
for a database.
public static string GetValue()
{
const string cacheKey = "CacheKey";
ObjectCache cache = MemoryCache.Default;
var cacheValue = cache[cacheKey];
if (cacheValue == null) // Null value means cache value doesn't exist/expired.
{
var value = "Value From External Resource";
// Create a cache policy that evicts the cache based on the absolute expiration policy.
var cachePolicy = new CacheItemPolicy
{
// Indicates whether a cache entry should be evicted at a specified point in time:
AbsoluteExpiration = DateTimeOffset.Now.Add(TimeSpan.FromMinutes(60)),
// Indicates whether a cache entry should be evicted if it has not been accessed in a given span of time:
SlidingExpiration = TimeSpan.FromMinutes(15)
};
// Update the cache based on the policy.
cache.Set(cacheKey, value, cachePolicy);
}
return (string)cacheValue;
}
ObjectCache
Methods
Add
: add an item, does not overwrite if it exists.
Set
: add an item, overwrite if exists.
Get
: return an item from the cache
AddOrGetExisting
: add an item, if it exists return what is already there.
Contains
: check if a key has an entry in the cache.
GetCount
: total number of entries in cache.
GetEnumerator
: can be used to iterate over all entries.
GetValues
: return a Set of values (takes an IEnumerable
of keys).
Remove
: remove a given cache entry.
public static string GetFileContents()
{
const string cacheKey = "FileContents";
ObjectCache cache = MemoryCache.Default;
if (cache[cacheKey] == null)
{
var filesToMonitor = new List<string>
{
"C:\\\\.Directory\\\\FileName1.txt",
"C:\\\\.Directory\\\\FileName2.txt"
};
// Create a cache policy to monitor a set of files.
// The policy will evict the cache value when any file changed.
var cachePolicy = new CacheItemPolicy();
cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(filesToMonitor));
// Update the cache based on the policy.
var fileContents = File.ReadAllText(filesToMonitor.First());
cache.Set(cacheKey, fileContents, cachePolicy);
}
return cache.Get(key);
}
SqlDependency
- The
SqlDependency
represents a query notification dependency between an application and an instance of SQL Server.