[英]Interlocked.Exchange Collection Modified Exception
我正在尝试创建一种缓冲输入形式,以了解不使用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的调用将返回新集合。 但是作品中似乎有一颗妖精...
调用Interlocked.Exchange(原子操作)后,调用_items将返回新集合
好吧,那是真的。 但是_items
的读取发生在对Interlocked.Exchange
的调用之前。
这行代码
_items.Enqueue(item);
变成多条MSIL指令,大致是:
ldthis ; really ldarg.0
ldfld _items
ldloc item
callvirt Queue<T>::Enqueue
如果InterlockedExchange
在第二条指令和第四条指令之间或在执行Enqueue
方法期间的任何时间发生,请BAM!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.