I am trying to create a form of Buffered Input to see how easy it would be to implement, without the use of Rx or any other library (outside standard .net 4.5). So I came up with the following class:
public class BufferedInput<T>
{
private Timer _timer;
private volatile Queue<T> _items = new Queue<T>();
public event EventHandler<BufferedEventArgs<T>> OnNext;
public BufferedInput() : this(TimeSpan.FromSeconds(1))
{
}
public BufferedInput(TimeSpan interval)
{
_timer = new Timer(OnTimerTick);
_timer.Change(interval, interval);
}
public void Add(T item)
{
_items.Enqueue(item);
}
private void OnTimerTick(object state)
{
#pragma warning disable 420
var bufferedItems = Interlocked.Exchange(ref _items, new Queue<T>());
var ev = OnNext;
if (ev != null)
{
ev(this, new BufferedEventArgs<T>(bufferedItems));
}
#pragma warning restore 420
}
}
The principal being, that once the timer ticks it switches the queues and carries on triggering the event. I realise that this could have been done with a list...
After a while i get the following, familiar, exception:
Collection was modified after the enumerator was instantiated.
On the following line:
public BufferedEventArgs(IEnumerable<T> items) : this(items.ToList())
The declaration and test program are:
public sealed class BufferedEventArgs<T> : EventArgs
{
private readonly ReadOnlyCollection<T> _items;
public ReadOnlyCollection<T> Items { get { return _items; } }
public BufferedEventArgs(IList<T> items)
{
_items = new ReadOnlyCollection<T>(items);
}
public BufferedEventArgs(IEnumerable<T> items) : this(items.ToList())
{
}
}
class Program
{
static void Main(string[] args)
{
var stop = false;
var bi = new BufferedInput<TestClass>();
bi.OnNext += (sender, eventArgs) =>
{
Console.WriteLine(eventArgs.Items.Count + " " + DateTime.Now);
};
Task.Run(() =>
{
var id = 0;
unchecked
{
while (!stop)
{
bi.Add(new TestClass { Id = ++id });
}
}
});
Console.ReadKey();
stop = true;
}
}
My thought was that after the call to Interlocked.Exchange
(an atomic operation) took place, a call to _items would return the new collection. But there seems to a gremlin in the works...