Skip to content
Permalink
Browse files

DirectoryWatcherBase - UpdateTwoFilesTwoSubscriptions

  • Loading branch information
bobbymcr committed Feb 10, 2020
1 parent ef84d2b commit 3236269feba33214b7925ed1900441c1850f7106
@@ -5,14 +5,13 @@
namespace DirectoryWatcherSample
{
using System;
using System.Collections.Concurrent;
using System.IO;

public abstract class DirectoryWatcherBase : IDisposable
{
private readonly string path;

private string file;
private Action<FileInfo> onUpdate;
private readonly ConcurrentDictionary<string, Subscription> subscriptions;

protected DirectoryWatcherBase(DirectoryInfo path)
{
@@ -22,12 +21,13 @@ protected DirectoryWatcherBase(DirectoryInfo path)
}

this.path = path.FullName;
this.subscriptions = new ConcurrentDictionary<string, Subscription>(StringComparer.OrdinalIgnoreCase);
}

public void Subscribe(string file, Action<FileInfo> onUpdate)
{
this.file = Path.Combine(this.path, file);
this.onUpdate = onUpdate;
FileInfo fullPath = new FileInfo(Path.Combine(this.path, file));
this.subscriptions[fullPath.FullName] = new Subscription(fullPath, onUpdate);
}

public void Dispose()
@@ -42,10 +42,24 @@ protected virtual void Dispose(bool disposing)

protected void OnUpdated(string fullPath)
{
if (string.Equals(this.file, fullPath, StringComparison.OrdinalIgnoreCase))
if (this.subscriptions.TryGetValue(fullPath, out Subscription subscription))
{
subscription.Invoke();
}
}

private struct Subscription
{
private readonly FileInfo fullPath;
private readonly Action<FileInfo> callback;

public Subscription(FileInfo fullPath, Action<FileInfo> callback)
{
this.onUpdate(new FileInfo(this.file));
this.fullPath = fullPath;
this.callback = callback;
}

public void Invoke() => this.callback(this.fullPath);
}
}
}
@@ -82,6 +82,23 @@ public void UpdateRelevantFileOneSubscriptionDifferentCase()
updates.Should().ContainSingle().Which.Should().Be(@"X:\root\file1.txt");
}

[TestMethod]
public void UpdateTwoFilesTwoSubscriptions()
{
List<string> updates = new List<string>();
FakeDirectoryWatcher watcher = new FakeDirectoryWatcher(new DirectoryInfo(@"X:\root"));
DirectoryWatcherBase watcherBase = watcher;
watcherBase.Subscribe("file1.txt", f => updates.Add(f.FullName));
watcherBase.Subscribe("file2.txt", f => updates.Add(f.FullName));

watcher.Update(@"X:\root\file2.txt");
watcher.Update(@"X:\root\file1.txt");

updates.Should().HaveCount(2).And.ContainInOrder(
@"X:\root\file2.txt",
@"X:\root\file1.txt");
}

private sealed class FakeDirectoryWatcher : DirectoryWatcherBase
{
public FakeDirectoryWatcher(DirectoryInfo path)

0 comments on commit 3236269

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