Sve*_*vek 3 c# linq concurrency
我不是 100% 的,所以我需要专家的意见。
ConcurrentQueue<object> queue = new ConcurrentQueue<object>();
List<object> listA = queue.ToArray().ToList(); // A
List<object> listB = queue.ToList(); // B
Run Code Online (Sandbox Code Playgroud)
我知道该ToArray()方法会复制一份(因为它是 内的一个内部方法ConcurrentQueue),但是ToList()直接调用该方法会做同样的事情吗?
简单地说,将代码从 A 重构到 B 是否安全?
如果我们查看源代码,我们会发现 GetEnumerator 也是线程安全的,所以我假设 A 和 B 都是线程安全的。
当您调用 .ToList() Linq 时调用 List 的构造函数
public List(IEnumerable<T> collection) {
Run Code Online (Sandbox Code Playgroud)
所以代码实际上使副本看起来像线程安全:
using(IEnumerator<T> en = collection.GetEnumerator()) {
while(en.MoveNext()) {
Add(en.Current);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
枚举器的评论也说我们可以同时使用它:
/// 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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2239 次 |
| 最近记录: |