File Dependency
File dependency provides a mechanism to invalidate the cache data in case of non-relational data sources. Here you can associate a file/folder dependency with a cache item. Whenever that file/folder is removed or modified, NCache will remove its dependent item from cache. Cache clean up (expiration) thread monitors the dependent file/folder for any change at every Clean Interval.
On cache clean up interval, NCache triggers dependency in the following scenarios:
- Dependency file/folder is removed/modified.
- Dependency file is replaced with directory and vice versa.
- Dependency is created in the non-existed file/folder, but on the cleanup interval it is created.
Similarly, multiple items can depend on a single file. Any change in file, either by updating the file or deletion, causes the cache to remove the dependent items from the cache. Likewise, an item can create dependency on multiple files in file dependency.
You can also mention a delay called "start after" in file dependency which indicates when to start monitoring the dependent file for any change. In this way NCache will start checking the dependent file after the "start after" time has elapsed.
To utilize the API, include the following namespace in your application:
Alachisoft.NCache.Runtime.Dependencies.
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";
string key = "Product:" + product.ProductID;
string filepath = "C:\\tempProductList.txt";
try{
//Adding cache item "Product:1001" with FileDependency on file "tempProductList.txt"
cache.Insert(key, product, new FileDependency(filepath), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal);
//Change file C:\\tempProductList.txt while program waits...
Thread.Sleep(5000);
//... and then check for its existence
Object item = cache.Get(key);
if (item == null){
// item removed successfully
}
else{
// item not removed successfully
}
}
catch (OperationFailedException e){ // handle exception
}