我正在尝试创建一种缓冲输入形式,以查看在不使用 Rx 或任何其他库(标准 .net 4.5 之外)的情况下实现它的难易程度。所以我想出了以下课程:
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
}
}
主要是,一旦计时器滴答作响,它就会切换队列并继续触发事件。我意识到这可以通过一个列表来完成......
过了一会儿,我得到以下熟悉的异常:
Collection was modified after the enumerator was instantiated.
在以下行:
public BufferedEventArgs(IEnumerable<T> items) : this(items.ToList())
声明和测试程序是:
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;
}
}
我的想法是,在调用Interlocked.Exchange
(原子操作)之后,调用 _items 将返回新集合。但是作品中似乎有一个小鬼……