问题描述
会发生什么事到了WeakReference当WeakReference.Target引用的目标对象被垃圾回收?是否WeakRerence生存并保持现有的?为什么我问的原因是我有存储在一个在WeakReferences列出的清单。在运行时新在WeakReferences不断越来越添加到列表中。现在,当目标对象死了,我要清理废弃的WeakReference自己?如果是这样,有一个聪明的把戏,我怎么能做到这一点?我可以得到通知时,一个WeakReference的成为抛弃?还是我来介绍一个计时器,经常通过该列表循环,看看是否有WeakReference的情况下,可以从列表中删除。
What happens to the WeakReference when the target object referenced by WeakReference.Target has been garbage collected? Does the WeakRerence stay alive and keeps existing?The reason why I am asking is that I have a list of WeakReferences stored in a List. During runtime new WeakReferences constantly are getting added to that list. Now when the target object dies, do I have to cleanup the abandoned WeakReference myself?If so, is there a clever trick how I could do this? Can I get notified when a WeakReference becomes abandoned? Or do I have to introduce a timer that frequently loops through that list, to see if any WeakReference instances can be removed from that list.
推荐答案
这是一个常见的问题与弱引用。基准本身仍然活着,因为它具有正常的指针到它。按照你的建议,你需要做一些手工垃圾收集不时。请注意,您也许可以清理存根对你的方式,当你遍历列表中的另一个原因。根据不同的使用模式的列表中,这个就在身边的垃圾收集,甚至可能是不够的。
This is a common problem with weak references. The reference itself remains alive because it has normal pointers to it. As you suggest, you need to do some "manual garbage collection" from time to time. Note that you can probably clean up the stubs on your way when you are traversing the list for another reason. Depending the use pattern for the list, this "on the side" garbage collection may even be enough.
在列表中不要频频循环清洁它的唯一目的!每死存根不仅浪费了几个记忆单词。如果列表中不经常使用经常清洗它的计算成本是没有道理的,如果是经常使用它会清理自己打扮成上面的建议。
Do not "frequently" loop through the list for the sole purpose of cleaning it up! Each dead stub only wastes a couple of words of memory. If the list is not used often the computational cost of cleaning it often is not justified, and if it is used frequently it will clean itself up as suggested above.
这是另一种垃圾收集系统共,但问题是如此的相似,你可能会感兴趣这篇文章如果你能得到它。
It's in another garbage-collected system altogether, but the problems are so similar that you may be interested in this article if you can get it.
这篇关于WeakReference.Target的GC之后发生一个WeakReference的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!