Interlocked.Exchange Collection修改过的异常

时间:2014-10-16 21:54:04

标签: c# multithreading buffer lockless

我正在尝试创建一种缓冲输入形式,以查看实现的容易程度,不使用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的调用将返回新的集合。但是在工作中似乎有一种瑕疵......

1 个答案:

答案 0 :(得分:1)

  

在调用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!