wasSharpNET – Blame information for rev 31
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
31 | office | 1 | using System; |
2 | using System.IO; |
||
3 | using System.Runtime.Caching; |
||
4 | |||
5 | namespace wasSharpNET.IO |
||
6 | { |
||
7 | /// <summary> |
||
8 | /// Filesystem watcher that ensures events are not fired twice |
||
9 | /// </summary> |
||
10 | /// <remarks>derived from Ben Hall @ benhall.io</remarks> |
||
11 | public class FileSystemWatcher : IDisposable |
||
12 | { |
||
13 | public event FileSystemEventHandler FilesytemEvent; |
||
14 | private readonly CacheItemPolicy _cacheItemPolicy; |
||
15 | private readonly int _cacheTimeMilliseconds = 1000; |
||
16 | private readonly MemoryCache _memCache; |
||
17 | |||
18 | public FileSystemWatcher(string path, NotifyFilters notifyFilters, string filter) |
||
19 | { |
||
20 | _memCache = MemoryCache.Default; |
||
21 | |||
22 | var watcher = new System.IO.FileSystemWatcher |
||
23 | { |
||
24 | Path = path, |
||
25 | NotifyFilter = notifyFilters, |
||
26 | Filter = filter |
||
27 | }; |
||
28 | |||
29 | _cacheItemPolicy = new CacheItemPolicy |
||
30 | { |
||
31 | RemovedCallback = OnRemovedFromCache |
||
32 | }; |
||
33 | |||
34 | watcher.Changed += OnChanged; |
||
35 | watcher.EnableRaisingEvents = true; |
||
36 | } |
||
37 | |||
38 | public FileSystemWatcher(string path, NotifyFilters notifyFilters, string filter, int timeout) : this(path, |
||
39 | notifyFilters, filter) |
||
40 | { |
||
41 | _cacheTimeMilliseconds = timeout; |
||
42 | } |
||
43 | |||
44 | // Add file event to cache for CacheTimeMilliseconds |
||
45 | private void OnChanged(object source, FileSystemEventArgs e) |
||
46 | { |
||
47 | _cacheItemPolicy.AbsoluteExpiration = |
||
48 | DateTimeOffset.Now.AddMilliseconds(_cacheTimeMilliseconds); |
||
49 | |||
50 | // Only add if it is not there already (swallow others) |
||
51 | _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy); |
||
52 | } |
||
53 | |||
54 | // Handle cache item expiring |
||
55 | private void OnRemovedFromCache(CacheEntryRemovedArguments args) |
||
56 | { |
||
57 | if (args.RemovedReason != CacheEntryRemovedReason.Expired) return; |
||
58 | |||
59 | // Now actually handle file event. |
||
60 | OnFileSystemEvent((FileSystemEventArgs)args.CacheItem.Value); |
||
61 | } |
||
62 | |||
63 | protected virtual void OnFileSystemEvent(FileSystemEventArgs e) |
||
64 | { |
||
65 | FilesytemEvent?.Invoke(this, e); |
||
66 | } |
||
67 | |||
68 | public void Dispose() |
||
69 | { |
||
70 | _memCache.Dispose(); |
||
71 | } |
||
72 | } |
||
73 | } |