如何使ENumerable操作安全可靠SynchronizedCollection?

问题描述 投票:0回答:2

当我使用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();
    }
}

It returns enumerator of inner List which is not thread safe

编辑。我不知道在并发情况下我能做些什么。我问

如何使其线程安全?

c# list asynchronous concurrency synchronization
2个回答
1
投票

我认为这有两个解决方案:

  1. 在System.Collections.Concurrent命名空间中使用ConcurrentBag<T>或其他集合。 (请注意,ConcurrentBag中的元素不会被排序。)
  2. 检索数据时创建快照。

第二个是性能成本更安全。

如果您使用的是.NetCore,ImmutableList<T>是一种更好的快照方式,可以避免浅拷贝问题。


0
投票

我使用了SynchronizedCollection类并在这里使用了foreach (var element in this.items) yield return element; public new IEnumerator GetEnumerator()

使用了基类的构造函数,这足以使它成为线程安全的

© www.soinside.com 2019 - 2024. All rights reserved.