局部范围后的'object'会发生什么? [英] What happens to 'object' after local scope?

查看:102
本文介绍了局部范围后的'object'会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我渴望知道.NET中的对象在超出范围时会发生什么。就像这样:

I am eager to know what happens to a object in .NET when it falls out of scope. Something like this:

class A
{
    ClassB myObjectB = new ClassB();
}
//what happens to object at this point here?

内存中会发生什么?如果GC在超出范围时被调用,并在堆中释放它的引用?

What happens in the memory? Does GC get called when it falls out of scope and loose it reference in the heap?

推荐答案


记忆中会发生什么?当GC超出范围并且在堆中引用它时,它会被调用吗?

What happens in the memory? Does GC get called when it falls out of scope and loose it reference in the heap?

否 - GC不会被调用在这一点上。

No - the GC doesn't get called at this point.

会发生什么是对象留在内存中,但现在是无根的 - 基本上,没有任何其他对象引用该对象。因此,该对象现在可用于垃圾收集。

What happens is that the object is left in memory, but is now "unrooted" - basically, there are no references to that object from any other object. As such, the object is now eligible for garbage collection.

在将来某个时候,GC将运行。发生这种情况时,无根对象现在将符合垃圾回收的条件。根据哪一代持有对象,它可能会或可能不会被清理。最后,如果程序继续执行,并且内存压力导致适当的一代被收集,则该对象的内存将被收回。

At some point in the future, the GC will run. When this happens, the unrooted object will now be eligible for garbage collection. Depending on which generation holds the object, it may or may not be cleaned at that point. Eventually, if the program continues executing and if memory pressure causes the appropriate generation to be collected, the memory for that object will be reclaimed.

没有确切的时间点当这种情况发生时(除非你明确地调用 GC.Collect ,这是一个坏主意)。但是,使用托管代码,您并不需要担心这种情况何时发生。假设它会在您的特定应用程序适用时发生。

There is no definite point in time when this will happen (unless you explicitly call GC.Collect, which is a bad idea). However, with managed code, you don't really need to worry about when this will happen. Just assume that it will happen when and if appropriate for your specific application.

这篇关于局部范围后的'object'会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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