Skip to content
Permalink
Browse files

DirectoryWatcher - reimplement using DirectoryWatcherBase

  • Loading branch information
bobbymcr committed Feb 10, 2020
1 parent ecf95b6 commit eef050ad622bee83886e5ba06199eddd8718b254
Showing with 4 additions and 58 deletions.
  1. +4 −58 projects/DirectoryWatcherSample/DirectoryWatcherSample.Core/DirectoryWatcher.cs
@@ -4,21 +4,16 @@

namespace DirectoryWatcherSample
{
using System;
using System.Collections.Concurrent;
using System.IO;

public sealed class DirectoryWatcher : IDisposable
public sealed class DirectoryWatcher : DirectoryWatcherBase
{
private readonly string path;
private readonly ConcurrentDictionary<string, Subscription> subscriptions;
private readonly FileSystemWatcher watcher;

public DirectoryWatcher(DirectoryInfo path)
: base(path)
{
this.path = path.FullName;
this.subscriptions = new ConcurrentDictionary<string, Subscription>(StringComparer.OrdinalIgnoreCase);
this.watcher = new FileSystemWatcher(this.path);
this.watcher = new FileSystemWatcher(path.FullName);
this.watcher.NotifyFilter =
NotifyFilters.FileName |
NotifyFilters.LastWrite |
@@ -29,55 +24,6 @@ public DirectoryWatcher(DirectoryInfo path)
this.watcher.EnableRaisingEvents = true;
}

public void Dispose() => this.watcher.Dispose();

public IDisposable Subscribe(string file, Action<FileInfo> onUpdate)
{
FileInfo fullPath = new FileInfo(Path.Combine(this.path, file));
if (!string.Equals(fullPath.DirectoryName, this.path, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(
"The file '{file}' is not directly within directory '{path}'.",
nameof(file));
}

string key = fullPath.FullName;
Subscription subscription = this.subscriptions.GetOrAdd(
key,
k => new Subscription(fullPath, onUpdate, () => this.subscriptions.TryRemove(k, out _)));
if (!object.ReferenceEquals(subscription.FullPath, fullPath))
{
throw new InvalidOperationException($"A subscription for '{key}' already exists.");
}

return subscription;
}

private void OnUpdated(string fullPath)
{
if (this.subscriptions.TryGetValue(fullPath, out Subscription subscription))
{
subscription.Invoke();
}
}

private sealed class Subscription : IDisposable
{
private readonly Action<FileInfo> callback;
private readonly Action onDispose;

public Subscription(FileInfo fullPath, Action<FileInfo> callback, Action onDispose)
{
this.FullPath = fullPath;
this.callback = callback;
this.onDispose = onDispose;
}

public FileInfo FullPath { get; }

public void Invoke() => this.callback(this.FullPath);

public void Dispose() => this.onDispose();
}
protected override void Dispose(bool disposing) => this.watcher.Dispose();
}
}

0 comments on commit eef050a

Please sign in to comment.
You can’t perform that action at this time.