对于远程处理框架,我需要保留一些关于要返回的对象的元数据。 我无法控制对象本身(所以我不能使它们成为 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 theConditionalWeakTable<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.
