2

I am attempting to use a file as a trigger to refresh my cached items. When the file is changed, I need to fire an event (every time the file changes). I'm currently using the HostFileChangeMonitor class. Here's where a cached item gets set, using a policy to link it to a file:

private static void SetPolicy(CacheNames cacheName, CacheItem item)
    {
        string strCacheName = cacheName.ToString();
        CacheItemPolicy policy;
        if (_policies.TryGetValue(strCacheName, out policy))
        {
            _cacheObject.Set(item, policy);
            return;
        }
        policy = new CacheItemPolicy();
        List<string> filePaths = new List<string> {
            string.Format(@"{0}\{1}.txt",Config.AppSettings.CachePath,cacheName.ToString())
        };
        var changeMonitor = new HostFileChangeMonitor(filePaths);
        _cacheObject.Set(item, policy);
        changeMonitor.NotifyOnChanged(new OnChangedCallback(RefreshCache));
        policy.ChangeMonitors.Add(changeMonitor);
    }

The NotifyOnChanged fires only once, however. Because of that, I am currently removing and then re-adding the item to the cache in the RefreshCache method called by the NotifyOnChanged:

private static void RefreshCache(object state)
    {
        //remove from cache
        WcfCache.ClearCache("Refreshed");
        //resubscribe to NotifyOnChanged event
        WcfCache.SetCache("Refreshed", true, CacheNames.CacheFileName);
        //grab all cache data and refresh each in parallel
}

Is there a better way to do this? Is there an event I can tap into that will ALWAYS fire (instead of just the first time like this NotifyOnChanged)? This seems pretty fragile. If the HostFileChangeMonitor doesn't get added properly one time, the entire app's cache will never refresh.

DougJones
  • 774
  • 1
  • 9
  • 26

2 Answers2

1

Have you tried the FileSystemWatcher and handling its Change event?Here's MSDN's documentation on the subject for more detailed info.

Sumo
  • 4,066
  • 23
  • 40
  • 1
    I hadn't used this before. That, combined with [this post](http://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice) enabled me to set it up correctly. Thanks! – DougJones Sep 06 '11 at 12:00
0

I've just discovered this class and from what I get, the NotifyOnChanged is not meant to be fired every time a watched file is updated (even though the name lets you think otherwise). Rather the file is constantly being watched and cached and you simply need to get it from the cache whenever you need it.

Etienne
  • 1,058
  • 11
  • 22