- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
对于远程处理框架,我需要保留一些关于要返回的对象的元数据。我无法控制对象本身(所以我不能使它们成为 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,
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,
TValue>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/
据我所知,不能保证 Object.finalize() 总是被调用。但是如果有重要的非GC资源,并且用户没有意外调用close(),我该如何释放该资源?PS。 .NET中的Object.Finaliz
我是一名优秀的程序员,十分优秀!