簡體   English   中英

如何使可枚舉操作能夠安全使用SynchronizedCollection?

[英]How to make ENumerable operations tread safe SynchronizedCollection?

當我使用SynchronizedCollection ,我可以捕獲異常

System.InvalidOperationException
Collection was modified; enumeration operation may not execute.

foreach周期中。

如果查看SynchronizedCollection類的源代碼,即在GetEnumerator方法中(實際上有兩個,其中一個是顯式接口實現),您將看到:

List<T> items;

IEnumerator IEnumerable.GetEnumerator()
{
    return ((IList)this.items).GetEnumerator();
}

public IEnumerator<T> GetEnumerator()
{
    lock (this.sync)
    {
        return this.items.GetEnumerator();
    }
}

它返回不是線程安全的內部List的枚舉器

編輯。 我問的不是在並發情況下該怎么辦。 我問

如何使其線程安全?

我認為有兩種解決方案:

  1. 在System.Collections.Concurrent命名空間中使用ConcurrentBag <T>或其他集合。 (注意,不會對ConcurrentBag中的元素進行排序。)
  2. 檢索數據時創建快照。

第二個方面的性能成本要安全得多。

如果您使用的是.NetCore,則ImmutableList <T>是快照的更好方法,並且可以避免淺拷貝問題。

我使用了SynchronizedCollection類,並使用了foreach (var element in this.items) yield return element; 這里公共新的IEnumerator GetEnumerator()

從基類使用構造函數,這足以使其成為線程安全的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM