枚举树时不需要的分配

Len*_*y D 0 .net c# .net-core

我在 C# 项目中使用 Jetbrains rider,并在调试时使用动态程序分析功能,并且我有一段代码在枚举树结构时显示高内存分配问题。

该树需要是线程安全的,因为它可以在枚举时被另一个线程写入。

这是似乎过度分配的违规代码,JetBrains 工具似乎认为问题是由于闭包对象引起的,但我不相信,它位于小对象堆上

public IEnumerator<TreeNode<T>> GetEnumerator()
{
    yield return this;

    if (this.children == null)
    {
        yield break;
    }

    // Copy the children in case the collection gets modified while reading
    var childrenCopy = new List<TreeNode<T>>(this.children);

    foreach (var child in childrenCopy)
    {
        foreach (var subChild in child)
        {
            yield return subChild;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

- 更新

我知道子副本将分配,但一旦超出范围,我希望它被释放而不是卡在小对象堆上

任何关于正在发生的事情的想法将不胜感激。

谢谢

Mar*_*ell 5

分配来自(失败的)防御副本:

// Copy the children in case the collection gets modified while reading
var childrenCopy = new List<TreeNode<T>>(this.children);
Run Code Online (Sandbox Code Playgroud)

该树需要是线程安全的,因为它可以在枚举时被另一个线程写入。

你的代码已经被破坏并且注定要失败。如果其他线程正在运行,即使在防御性复制操作期间,它们也可能会更改数据。