c# - 如何使 ENumerable 操作踏上安全的 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();
}
}
编辑。我问的不是在并发情况下我能做什么。我在问
如何使其线程安全?
解决方案
我认为有两种解决方案:
- 在 System.Collections.Concurrent 命名空间中使用ConcurrentBag<T>或其他集合。(注意 ConcurrentBag 中的元素不会被排序。)
- 检索数据时创建快照。
在性能成本方面,第二个更安全。
如果您使用的是 .NetCore,ImmutableList<T>是一种更好的快照方式,并且可以避免浅拷贝问题。
推荐阅读
- php - PHP Try Ask , 如何避免多个 try ask 函数
- mysql - 如何将更多值添加到声明的变量中?
- discord.js - discord.js 中的消息计数?
- r - “-”和“/”是什么意思?
- python-3.x - 使用 du -sb 和 python psutil.disk_usage 获得不同的输出
- flutter - 设计带有图像和文本的 Flutter 按钮
- javascript - 从文本框中获取部分文本
- apache-zookeeper - 为什么 Zookeeper 无法运行?
- spring - OMDb API:搜索电影标题返回 null
- vue.js - 在没有 nodejs、webpack 或 npm 的情况下将 VueJS 集成到 ASP.NET Core