Created
November 26, 2012 09:56
-
-
Save deanhume/4147456 to your computer and use it in GitHub Desktop.
File Change Monitor - .NET cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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