Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created November 26, 2012 09:56
Show Gist options
  • Save deanhume/4147456 to your computer and use it in GitHub Desktop.
Save deanhume/4147456 to your computer and use it in GitHub Desktop.
File Change Monitor - .NET cache
private ObjectCache _cache = MemoryCache.Default;
private CacheItemPolicy _policy = new CacheItemPolicy();
public string RetrieveFileContents()
{
// Build a key that we can use to cache the contents in memory against
const string cacheKey = "fileContents";
// Check if the data exists in cache
string fileContents = _cache.Get(cacheKey) as string;
// If it is null, then go and fetch it
if (string.IsNullOrEmpty(fileContents))
{
using (StreamReader streamReader = new StreamReader(@"C:\ImportantFile.xml"))
{
fileContents = streamReader.ReadToEnd();
}
// Add back into cache with the dependency
_policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { @"C:\ImportantFile.xml"}));
_cache.Add(cacheKey, fileContents, _policy);
}
return fileContents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment