c# - 需要不强制数据一致性的高性能 C# 集合
问题描述
我处于具有大型(很多大型对象)静态集合的大规模并行环境中。
我找不到任何不强制数据一致性的集合实现。他们都尝试使用内部锁定、版本控制(例如:List)或本地复制(例如:ConcurrentBag)来强制执行它。
List<T>
效果很好,但使用版本控制和 Throw aInvalidOperation_EnumFailedVersion
ConcurrentBag<T>
在我的代码中显示性能下降。它是 GC 密集型的,并假设一个生产者/消费者模式。出于数据一致性目的,它遍历包的“快照”(ThreadLocal),但我的内存受限。- 我检查了上述两个集合的源代码
Net Framework
。Net Core
我需要一个具有以下功能的集合:
- 不要在任何时候隐式锁定。我会自己上锁。
- 不要抛出任何异常,因为我正在读取的数据可能不一致(非原子操作),我知道,没关系。
- 不要复制自己
- 需要是可变的
- 需要能够添加/删除一个元素(这可能需要一个明确的锁,我可以在这种罕见的情况下使用锁)
- 大小在编译时是未知的,最大大小是“直到系统内存不足和程序崩溃”。(无数组)
- 可用于 foreach 和 Parallel.ForEach
- 不需要订购
- 可以被多个线程读取,可以被多个线程同时写入。无论任何可能的数据一致性问题。(它不能在内部使用“版本”)
LinkedList<T>
很有希望,但它似乎具有与 List 相同的“版本”一致性保护,来自源代码(https://github.com/dotnet/runtime/blob/master/src/libraries/System.Collections/src/System /Collections/Generic/LinkedList.cs#L564):
if (_version != _list.version)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
我需要创建自己的实现吗?
解决方案
您仍然可以使用 a ,并使用循环List<T>
枚举它,处理可能发生的任何异常:for
ArgumentOutOfRangeException
public static IEnumerable<T> AsInconsistentEnumerable<T>(this List<T> list)
{
for (int i = 0; i < list.Count; i++)
{
T current;
try
{
current = list[i];
}
catch (ArgumentOutOfRangeException)
{
yield break;
}
yield return current;
}
}
使用示例:
foreach (var item in myList.AsInconsistentEnumerable())
{
//...
}
关于这个集合的大小,通过在 App.config 中Int32.MaxValue
配置选项,您可以在 64 位平台上添加多达 20 亿个元素 ( )。gcAllowVeryLargeObjects
推荐阅读
- ethereum - is not contract address during truffle test
- javascript - 如何在 Laravel 中为可拖动列实现 AJAX
- powershell - “以不同的用户身份运行”与 PowerShell 的行为不同
- ios - Mysterious green overlay on iPad map
- here-api - 此处跟踪无法添加设备
- python - 没有标题的 CSV 中的 Pandas 绘图图
- javascript - how do i make the width of the label on free contact form wider?
- javascript - 如何从(0,0)开始获取具有长度和角度的二维坐标
- c# - 强制保存 Sitefinity 小部件 MVC 控制器属性
- c# - 您可以自动将“this”作为参数传递吗?