gpt4 book ai didi

c# - 对象终结或垃圾收集事件

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:54 24 4
gpt4 key购买 nike

对于远程处理框架,我需要保留一些关于要返回的对象的元数据。我无法控制对象本身(所以我不能使它们成为 IDisposable),我也不知道它们的类型。我唯一的假设是它是一个引用类型。

问题是生命周期,我什么时候释放我的元数据。

我打算创建一个静态字典 (ConcurrentDictionary) 并在其中保存对对象和元数据的 WeakReference。问题是,我怎么知道什么时候删除元数据?有没有办法在对象本身完成时接收通知?

我也不关心死灵法术(物体复活)

谢谢

最佳答案

如果您使用的是 .NET4 或更高版本,您可以使用 ConditionalWeakTable<K,V> .

这意味着您(可能)不需要担心自己释放元数据:一旦对象本身消失,它就会从表中消失。

The ConditionalWeakTable<TKey, TValue> class differs from other collection objects in its management of the object lifetime of keys stored in the collection. Ordinarily, when an object is stored in a collection, its lifetime lasts until it is removed (and there are no additional references to the object) or until the collection object itself is destroyed. However, in the ConditionalWeakTable<TKey,
TValue>
class, adding a key/value pair to the table does not ensure that the key will persist, even if it can be reached directly from a value stored in the table (for example, if the table contains one key, A, with a value V1, and a second key, B, with a value P2 that contains a reference to A). Instead, ConditionalWeakTable<TKey, TValue> automatically removes the key/value entry as soon as no other references to a key exist outside the table.

关于c# - 对象终结或垃圾收集事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9788752/

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