Wednesday, March 28, 2012

System.Runtime.Caching (.Net 4.0)

.Net 4.0 introduced the System.Runtime.Caching namespace, this made developers to make use of caching functionality independent of the cache found in the System.Web DLL.
Caching using the System.Runtime.Caching provides an in memory cache but also allows developers to extend this with a different provider. For an example, you could have an implementation that could hold the items in memory but also persists it into the hard disk for the fear of cache eviction.

Adding an item into the cache is done this way...

//Get the default cache
MemoryCache cache = MemoryCache.Default;

//Add the item

cache.Add("MyKey",

"Nairooz Nilafdeen",

DateTimeOffset.Now.AddMinutes(19));

//Get the item from the cache

if (cache.Contains("MyKey"))

{

Console.WriteLine(cache.Get("MyKey"));

}


The caching namespace also allows you to set ChangeMonitors for the cache policy, for an example, you can specify that the cache needs to expire once a file changes or the database query changes..
You can watch for a file and expire the cache after a specified time period (absolute or sliding) or when the file content changes...the code below demonstrates this.

string fileName = @"C:\ERR_LOG.log";

CacheItemPolicy policy = new CacheItemPolicy();

policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(40);

policy.ChangeMonitors.Add(new HostFileChangeMonitor

(new List<string> {fileName }));


cache.Add("FileKey", "Nairooz Nilafdeen", policy);


You can also attach a SqlDependency with the SqlChangeMonitor to expire the cache when a the result of a watched query changes...

SqlDependency dependency = new SqlDependency();

//initialize sql dependency heree...

policy.ChangeMonitors.Add(new SqlChangeMonitor(dependency));

No comments:

Post a Comment