垃圾收集器C#中,关于“清算”的对象问题 [英] Garbage Collector C#, question about 'clearing' objects
问题描述
我也读到了垃圾收集一些信息(它是如何的作品等)。我试图理解它是如何工作的做我的例子,但我觉得我有问题。我知道垃圾收集器运行时:B您调用GC.Collect()结果
内存不够,结果$ B $。结果
这是我的代码:
I read some informations about Garbage Collection (how it's works etc.). I tried understand how it's working doing my examples but I think I have problem. I know Garbage Collector runs when:
is not enough memory,
you call GC.Collect().
This is my code:
public partial class Form1 : Form
{
public Testing _d;
public Boolean _first = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!_first)
{
_d = new Testing();
int test = _d.DoSomething("example");
}
}
private void button2_Click(object sender, EventArgs e)
{
_first = true;
}
private void button3_Click(object sender, EventArgs e)
{
//if (_first)
//{
// _d = null;
//}
GC.Collect();
}
}
public class Testing
{
private ASCIIEncoding _ascii;
private bool _disposed = false;
public Testing()
{
_ascii = new ASCIIEncoding();
}
public int DoSomething(string message)
{
return _ascii.GetByteCount(message);
}
}
当我点击按钮1,我创建新的对象测试。 _D是参考这个新的对象。我在使用反倾销JetBrains公司dotTrace内存内存,看到这个新对象存在。点击按钮2之后,我布尔_first以_D变得无法访问设置为true。在这一点上,我想,当我运行GC.Collect的()GC将清除这个对象从堆栈,但我看到它仍然存在。我误解了有关GC的工作?或者说我这样做不对结果
它的工作当我设置 _D = NULL;
When I click button1 I'm creating new object Testing. _d is reference to this new object. I'm dumping memory using JetBrains dotTrace Memory and see this new object exists. After click button2 I'm setting boolean _first to true in order to _d became unreachable. At this point I thought when I run GC.Collect() GC will 'clear' this object from stack, but I see it's still exists. I misunderstood about GC work? or I'm doing this wrong?
It's working when I set _d = null;
推荐答案
设置第一= FALSE
不作 _D
实例无法访问在在GC的条款。从逻辑上讲,你可能永远不会再使用它,但它仍然是在 Form1中
类引用。
Setting first=false
does not make the _d
instance unreachable in terms of the the GC. Logically you may never use it again but it is still referenced in the Form1
class.
如果有人设置第一= TRUE
再次,你不能指望对象仍然是可用的?
If someone were to set first=true
again, would you not expect the object to still be usable?
这篇关于垃圾收集器C#中,关于“清算”的对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!