Skip to content
Permalink
Browse files

BatchedEvents - AddTwoAndComplete

  • Loading branch information
bobbymcr committed Feb 19, 2020
1 parent ec5dfac commit b949d05a725920d282bb01c441c6263686abdec6
@@ -5,32 +5,39 @@
namespace DirectoryWatcherSample
{
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

public sealed class BatchedEvents<T>
{
private readonly Func<Task> delay;
private readonly ConcurrentDictionary<T, TimePoint> batches;

private Action<T> callback;

public BatchedEvents(Func<Task> delay)
{
this.delay = delay;
this.batches = new ConcurrentDictionary<T, TimePoint>();
}

public void Subscribe(T item, Action<T> callback)
{
this.callback = callback;
this.batches.TryAdd(item, default);
}

public void Add(T item, TimePoint timestamp)
{
this.OnBatchCreated(item);
if (this.batches.TryUpdate(item, timestamp, default))
{
this.OnBatchCreated(item);
}
}

private void OnBatchCreated(T item)
{
this.delay().ContinueWith(t => this.callback(item));
this.delay().ContinueWith(t => this.callback(item), TaskContinuationOptions.ExecuteSynchronously);
}
}
}
@@ -39,5 +39,23 @@ public void AddOneAndComplete()

batches.Should().ContainSingle().Which.Should().Be("item1");
}

[TestMethod]
public void AddTwoAndComplete()
{
TaskCompletionSource<bool> pending = new TaskCompletionSource<bool>();
BatchedEvents<string> events = new BatchedEvents<string>(() => pending.Task);
List<string> batches = new List<string>();

events.Subscribe("item1", i => batches.Add(i));
events.Add("item1", new TimePoint(1));
events.Add("item1", new TimePoint(2));

batches.Should().BeEmpty();

pending.SetResult(true);

batches.Should().ContainSingle().Which.Should().Be("item1");
}
}
}

0 comments on commit b949d05

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