In a previous blog post, I wrote about the built in support that .NET has for in-memory caching. It sits under the System.Runtime.Caching namespace and can be easily added to any application to give you a great improvement in performance. You can store any type of object in the cache and this makes it extremely useful for storing different types of data.
In this post, we are going to run through a very handy feature that is built into the System.Runtime.Caching namespace - FileChangeMonitor. As the name suggests, FileChangeMonitor will monitor the contents of a file and respond as soon as any changes are made to that file. Instead of having your cache expire at a certain date or time, you can add a file dependency to your cache using the FileChangeMonitor. It means that when the contents of a certain file change, your cache becomes invalidated and you will need to retrieve a fresh copy. This is ideal for certain situations where you might be caching the contents of a file and don't want to stop and restart your entire application just for the changes to take effect.
Let's take a closer look at an example the FileChangeMonitor in action. The following snippet contains the code that is needed to add a file into cache using the FileChangeMonitor.
In line 1, we are obtaining a reference to the default MemoryCache instance. The following line contains a reference to the CacheItemPolicy that we will be using as a reference to store the data with. Using the _cache.Get method in line 10, we are trying to retrieve the data from the cache based on the cache key. If nothing is found, then we simply try and read the contents of the file and add it into cache.
The most important part to notice here is this line
_policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List
Here, we are adding a FileChangeMonitor into the list of ChangeMonitors that will be stored against the data in the cache. This important piece of information will be used to check if the contents of the file have changed and if so it will invalidate the cache. This will cause the null check on line 14 to fail and a new version of the contents will be read from the file.
The flow of logic for the above piece of code might look something like the image below
It's that easy! I have found this .NET feature to be very helpful when dealing with caching. I hope after reading this that it benefits you too!
Add your comment