垃圾回收:是否需要在 Dispose 方法中将大对象设置为 null? [英] Garbage Collection: Is it necessary to set large objects to null in a Dispose method?

查看:37
本文介绍了垃圾回收:是否需要在 Dispose 方法中将大对象设置为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现Dispose()方法时,是否需要将大对象设置为null?

Is it necessary to set large objects to null when implementing a Dispose() method?

推荐答案

通常不会.

垃圾收集器查找有根对象,如果两个对象都没有根,循环依赖不会阻止收集.

The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted.

有一个警告:如果对象 A 具有对对象 B 的引用,并且对象 B 正在被释放,您可能需要清理该关系,否则您可能会导致泄漏.这个表面最常见的地方是在事件处理程序中(来自 A->B 的引用是 B 控制的,因为它订阅了 A 上的事件).在这种情况下,如果 A 仍然有根,那么即使 B 已经被释放,也无法回收.

There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.

这篇关于垃圾回收:是否需要在 Dispose 方法中将大对象设置为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆