C#:在什么情况下你应该清空引用? [英] C#: In what cases should you null out references?

查看:143
本文介绍了C#:在什么情况下你应该清空引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


CLR Profiler还可以显示哪些方法分配的存储空间比预期的多,并且可以发现无意中保留引用无用的对象图的情况,否则这些对象图可能会被GC回收。 (一个常见的问题设计模式是一个软件缓存或查找表,它们不再需要或者以后可以重新安全地使用,当缓存使对象图在其有效期内保持活跃状态​​时是悲剧性的,相反,一定要将不再需要的对象引用为空。) - 写得更快托管代码

我认为我以前真的没有提及过某个参考。我假设你并不总是需要这样做,但我想也有些时候记住要做到这一点很重要。但是,那是什么情况?什么时候应该清空引用?

I don't think I've really ever nulled out a reference before. I assume you don't always need to do this, but I guess there also are times when it is important to remember to do it. But, what cases is that? When should you null out references?

推荐答案

只有当持有引用的变量保持活动状态 但你不希望引用本身来阻止垃圾收集。换句话说,如果对象A持有对象B的引用,并且您不再需要B,但A会因其他原因而保持活动状态。另一个常见的例子是静态变量,只要AppDomain是活着的。

You only need to do it when the variable holding the reference is going to stay "alive" but you don't want the reference itself to prevent garbage collection. In other words, if object A holds a reference to object B, and you don't need B any more but A will stay alive for other reasons. Another common example is static variables, which are "alive" for as long as the AppDomain is.

对于局部变量,它几乎不需要,因为GC可以检测代码中最后一个可能访问变量的点。但是,如果您在第一次迭代期间使用在循环外部声明的变量,但是您知道在后续迭代中不需要它,您可以将其设置为null以帮助该对象变为符合条件GC早些时候。

For local variables it's almost never needed, because the GC can detect the last possible point in code where a variable will be accessed. However, if you use a variable declared outside a loop during the first iteration, but you know you won't need it for subsequent iterations, you could set that to null to help the object to become eligible for GC earlier.

根据我的经验,在这种情况下很难找到自己。为了GC的缘故,我几乎没有将设置变量设为null。通常,对象中的所有成员变量都是有用的,直到对象本身变为符合GC的条件。如果您发现自己的成员变量在整个生命周期中不是,您可能需要查看它是否表示设计有问题。

In my experience it's very rare to find myself in this situation. I hardly ever deliberate set variables to null for the sake of the GC. Usually all the member variables within an object are "useful" until the object itself becomes eligible for GC. If you find yourself with member variables which aren't useful for the whole lifetime of the object, you might want to see whether that indicates a problem with the design.

这篇关于C#:在什么情况下你应该清空引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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