gpt4 book ai didi

c# - ConditionalWeakTable 是否应该用于非编译器目的?

转载 作者:IT王子 更新时间:2023-10-29 04:09:46 24 4
gpt4 key购买 nike

我最近遇到了 ConditionalWeakTable<TKey,TValue> 在我搜索 IDictionary 的类(class)中它使用弱引用,如答案 here 中所建议的那样和 here .

a definitive MSDN article其中介绍了该类(class)并指出:

You can find the class ... in the System.Runtime.CompilerServices namespace. It’s in CompilerServices because it’s not a general-purpose dictionary type: we intend for it to only be used by compiler writers.

然后又是:

...the conditional weak table is not intended to be a general purpose collection... But if you’re writing a .NET language of your own and need to expose the ability to attach properties to objects you should definitely look into the Conditional Weak Table.

与此相符,该类的 MSDN 条目描述如下:

Enables compilers to dynamically attach object fields to managed objects.

很明显,它最初是为一个非常具体的目的而创建的——帮助 DLR,以及 System.Runtime.CompilerServices命名空间体现了这一点。但它似乎找到了比这更广泛的用途——甚至在 CLR 中也是如此。如果我搜索 ConditionalWeakTable 的引用资料在 ILSpy ,例如,我可以看到在 MEF 类中使用了 CatalogExportProvider 并在内部 WPF DataGridHelper类等。

我的问题是是否可以使用ConditionalWeakTable在编译器编写和语言工具之外,以及这样做是否存在任何风险,即在未来的 .NET 版本中产生额外的开销或实现发生重大变化。 (或者应该避免使用 this one 之类的自定义实现来代替)。

还有延伸阅读here , herehere关于如何ConditionalWeakTable使用 ephemerons 的隐藏 CLR 实现(通过 System.Runtime.Compiler.Services. DependentHandle )处理键和值之间的循环问题,以及如何以自定义方式轻松实现这一点。

最佳答案

我没有发现使用 ConditionalWeakTable 有什么问题。如果您需要临时表,您几乎别无选择。

我认为 future 的 .NET 版本不会成为问题 - 即使只有编译器会使用此类,Microsoft 仍然无法在不破坏与现有二进制文件的兼容性的情况下更改它。

至于开销 - 与普通字典相比肯定会有开销。拥有许多 DependentHandle 可能会很昂贵,类似于有多少 WeakReference 比普通引用更昂贵(GC 必须做额外的工作来扫描它们以查看它们是否需要被清零)。但这不是问题,除非您有很多(几百万)个条目。

关于c# - ConditionalWeakTable<TKey, TValue> 是否应该用于非编译器目的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10225727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com