ConcurrentQueue ToList()vs ToArray()。ToList()

时间:2018-01-31 12:39:02

标签: c# linq concurrency

我不是百分之百,所以我想要专家的意见。

ConcurrentQueue<object> queue = new ConcurrentQueue<object>();

List<object> listA = queue.ToArray().ToList();   // A
List<object> listB = queue.ToList();             // B

我了解ToArray()方法会复制(因为它是ConcurrentQueue中的内部方法),但是调用ToList()方法会直接做同样的事情吗?

简单地说,将代码从A重构为B是否安全?

1 个答案:

答案 0 :(得分:2)

如果我们查看源代码,我们会看到GetEnumerator也是线程安全的,所以我认为A和B都是线程安全的。

当你调用.ToList()时,Linq调用List

的构造函数
 public List(IEnumerable<T> collection) {

因此代码实际上使副本看起来像线程安全:

        using(IEnumerator<T> en = collection.GetEnumerator()) {
            while(en.MoveNext()) {
                Add(en.Current);                                    
            }

source code of ConcurrentQueue

source code of List

public IEnumerator<T> GetEnumerator()
{
    // Increments the number of active snapshot takers. This increment must happen before the snapshot is 
    // taken. At the same time, Decrement must happen after the enumeration is over. Only in this way, can it
    // eliminate race condition when Segment.TryRemove() checks whether m_numSnapshotTakers == 0. 
    Interlocked.Increment(ref m_numSnapshotTakers);

    // Takes a snapshot of the queue. 
    // A design flaw here: if a Thread.Abort() happens, we cannot decrement m_numSnapshotTakers. But we cannot 
    // wrap the following with a try/finally block, otherwise the decrement will happen before the yield return 
    // statements in the GetEnumerator (head, tail, headLow, tailHigh) method.           
    Segment head, tail;
    int headLow, tailHigh;
    GetHeadTailPositions(out head, out tail, out headLow, out tailHigh);

    //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
    // the queue is not taken when GetEnumerator is initialized but when MoveNext() is first called.
    // This is inconsistent with existing generic collections. In order to prevent it, we capture the 
    // value of m_head in a buffer and call out to a helper method.
    //The old way of doing this was to return the ToList().GetEnumerator(), but ToList() was an 
    // unnecessary perfomance hit.
    return GetEnumerator(head, tail, headLow, tailHigh);
}

普查员的评论也说我们可以巧妙地使用它:

    /// The enumeration represents a moment-in-time snapshot of the contents
    /// of the queue.  It does not reflect any updates to the collection after 
    /// <see cref="GetEnumerator"/> was called.  The enumerator is safe to use
    /// concurrently with reads from and writes to the queue.