How to Prevent File Change Event Firing Twice?
I love the library, however, I am finding that the FileChanged event is being fired multiple times for single save operations. This is normal for the Microsoft FileSystemWatcher but I wondered if you have addressed this yourself to stop it from happening? If not, do you have any advice for me to amend the library to stop it from happening?
Thanks for your time.
I've not used this library in particular, but I have implemented a workaround for the native filesystem watcher (which I thought was pretty neat, albeit slightly hacky): Use MemoryCache
If you create cache items with a sliding expiration based on the name of the file affected by the events being received, the cache will automatically purge the items when they expire. This means you can set a sliding expiration for between 250 and 1000ms and use it to effectively debounce/throttle the events for that file, without doing any timing logic yourself
e.g. I had logic like this
public bool HasRecentEvent(string absoluteFilename, int thresholdSeconds = 2)
{
return (_events.AddOrGetExisting(absoluteFilename, new object(), new CacheItemPolicy
{
SlidingExpiration = TimeSpan.FromSeconds(thresholdSeconds)
}) != null);
}
where I would just drop the event if HasRecentEvent returned true
All this required was a memory cache instance. What's more is that memory cache is thread safe provided you're only doing simple operations like AddOrGet etc.
Edit: just to clarify, I'm not saying this is some panacea of a solution, but I thought it was pretty decent on a lines of code vs. effectiveness scale
This is clever. Maybe do a pull request and implement your solution internally somehow?
That is quite clever. If I manage to set a couple hours off in the near future I'll have a look at it. If not I'd be happy to pull any code in :)