首页 > 解决方案 > 需要不强制数据一致性的高性能 C# 集合

问题描述

我处于具有大型(很多大型对象)静态集合的大规模并行环境中。

我找不到任何不强制数据一致性的集合实现。他们都尝试使用内部锁定、版本控制(例如:List)或本地复制(例如:ConcurrentBag)来强制执行它。

我需要一个具有以下功能的集合:

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);
}

我需要创建自己的实现吗?

标签: c#multithreading.net-core

解决方案


您仍然可以使用 a ,并使用循环List<T>枚举它,处理可能发生的任何异常:forArgumentOutOfRangeException

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


推荐阅读