What happens to a WeakReference after GC of WeakReference.Target

泄露秘密 提交于 2019-12-10 12:48:03

问题


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.


回答1:


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.




回答2:


Since you have a strong reference to the WeakReference object, it will not get GC'ed. This is also by design, because it was intended that you can still use the WeakReference to find out that the target has been GC'ed.

So yes, you'll have to go the timer way.

Added: You might also take a look at Garbage Collection Notifications.



来源:https://stackoverflow.com/questions/1813740/what-happens-to-a-weakreference-after-gc-of-weakreference-target

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!